Spring Core基础教程

Spring框架简介

Spring框架是一个开源的Java平台,为开发Java企业应用提供全面的基础架构支持。Spring的核心特性可以用于开发任何Java应用程序,它的模块化设计使开发者可以只使用需要的部分。Spring框架的核心是控制反转(IoC)容器和面向切面编程(AOP)。

控制反转(IoC)与依赖注入(DI)

什么是IoC

控制反转是一种设计原则,它反转了传统程序设计中控制流程的方向。在传统程序设计中,我们的代码直接控制对象的创建和管理;而在IoC模式下,这种控制权被转移到了Spring容器。

什么是依赖注入

依赖注入是IoC的一种实现方式,它是指组件之间的依赖关系由容器在运行期决定,即由容器动态地将某个依赖关系注入到组件之中。

IoC容器的类型

Spring提供了两种类型的IoC容器:

  • BeanFactory - 最简单的容器,提供基本的DI支持
  • ApplicationContext - 建立在BeanFactory之上,提供更多企业级功能

Bean的配置与管理

XML配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">

<!-- 定义一个bean -->
<bean id="userService" class="com.example.service.UserServiceImpl">
<!-- 构造函数注入 -->
<constructor-arg ref="userRepository" />

<!-- 属性注入 -->
<property name="maxUsers" value="100" />
</bean>

<bean id="userRepository" class="com.example.repository.JdbcUserRepository">
<!-- 更多配置... -->
</bean>
</beans>

基于注解的配置

1
2
3
4
5
6
7
8
9
10
11
12
13
@Configuration
public class AppConfig {

@Bean
public UserRepository userRepository() {
return new JdbcUserRepository();
}

@Bean
public UserService userService() {
return new UserServiceImpl(userRepository());
}
}

组件扫描与自动装配

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
@Configuration
@ComponentScan("com.example")
public class AppConfig {
// 配置类的内容可以为空,组件会通过扫描自动注册
}

@Component
public class UserServiceImpl implements UserService {

private final UserRepository userRepository;

@Autowired
public UserServiceImpl(UserRepository userRepository) {
this.userRepository = userRepository;
}

// 业务方法...
}

@Repository
public class JdbcUserRepository implements UserRepository {
// 实现方法...
}

Spring常用注解

组件注册

  • @Component - 通用组件
  • @Service - 业务逻辑层组件
  • @Repository - 数据访问层组件
  • @Controller - 控制器组件(Web层)
  • @RestController - RESTful Web服务控制器组件

依赖注入

  • @Autowired - 自动装配依赖
  • @Qualifier - 指定要注入的特定bean
  • @Resource - JSR-250标准的资源注入
  • @Inject - JSR-330标准的依赖注入
  • @Value - 注入简单值,如属性文件中的配置

配置相关

  • @Configuration - 标记一个类为配置类
  • @Bean - 定义一个bean
  • @ComponentScan - 启用组件扫描
  • @PropertySource - 引入属性文件
  • @Profile - 指定bean在哪些环境配置下生效

Bean的生命周期

  1. 实例化 - 创建bean实例
  2. 属性赋值 - 设置bean属性
  3. 初始化前 - 调用BeanPostProcessor的前置处理方法
  4. 初始化 - 调用InitializingBean接口的afterPropertiesSet方法或自定义init-method
  5. 初始化后 - 调用BeanPostProcessor的后置处理方法
  6. 使用bean - bean可以被应用程序使用
  7. 销毁 - 调用DisposableBean接口的destroy方法或自定义destroy-method
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
@Component
public class ExampleBean implements InitializingBean, DisposableBean {

@PostConstruct
public void postConstruct() {
System.out.println("@PostConstruct方法执行");
}

@Override
public void afterPropertiesSet() throws Exception {
System.out.println("InitializingBean的afterPropertiesSet方法执行");
}

@PreDestroy
public void preDestroy() {
System.out.println("@PreDestroy方法执行");
}

@Override
public void destroy() throws Exception {
System.out.println("DisposableBean的destroy方法执行");
}
}

基于Java的配置示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
@Configuration
@PropertySource("classpath:app.properties")
@ComponentScan("com.example")
public class AppConfig {

@Value("${database.url}")
private String databaseUrl;

@Value("${database.username}")
private String username;

@Value("${database.password}")
private String password;

@Bean
public DataSource dataSource() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setUrl(databaseUrl);
dataSource.setUsername(username);
dataSource.setPassword(password);
return dataSource;
}

@Bean
public JdbcTemplate jdbcTemplate(DataSource dataSource) {
return new JdbcTemplate(dataSource);
}

@Bean
@Profile("development")
public CacheManager developmentCacheManager() {
return new SimpleCacheManager();
}

@Bean
@Profile("production")
public CacheManager productionCacheManager() {
return new ConcurrentMapCacheManager();
}
}

Spring表达式语言(SpEL)

Spring表达式语言是一个强大的表达式语言,支持在运行时查询和操作对象图:

1
2
3
4
5
6
7
8
9
10
11
12
@Component
public class ExampleBean {

@Value("#{systemProperties['user.region']}")
private String region;

@Value("#{userService.findUser(1)?.username}")
private String username;

@Value("#{T(java.lang.Math).random() * 100.0}")
private double randomNumber;
}

使用ApplicationContext

1
2
3
4
5
6
7
8
9
10
11
12
// 从XML加载ApplicationContext
ApplicationContext context =
new ClassPathXmlApplicationContext("applicationContext.xml");

// 或者从Java配置类加载
ApplicationContext context =
new AnnotationConfigApplicationContext(AppConfig.class);

// 获取bean
UserService userService = context.getBean("userService", UserService.class);
// 或者直接按类型获取
UserService userService = context.getBean(UserService.class);

总结

Spring Core是Spring框架的核心部分,它提供了强大的IoC容器和依赖注入机制,极大简化了Java应用程序的开发。通过理解和掌握Spring Core的基础知识,开发者可以更好地使用Spring框架的其他模块,如Spring MVC、Spring Data、Spring Security等,构建功能强大、易于维护的企业级Java应用程序。