1、概述
1.1、由来
Spring IOC中有个重要的概念——Bean,Bean即对象,我们通过配置Bean让IOC容器管理Bean,而最常用的方式就是通过XML文件来配置,但通过XML文件来配置比较繁琐,数量较多的时候会使项目变得复杂,而且使用XML配置没有编译时的类型安全检查
所以在Spring4以后,Spring推荐使用Java Config代替XML文件来配置Bean
Java Config就是使用注解,通过java类来描述Bean配置的组件
Java Config结合了XML的解耦和JAVA编译时检查的优点,可以看成是一个XML文件,只不过是由Java编写的
1.2、优缺点
1.2.1、优点
- 摒弃xml配置文件,使用Java类管理对象和依赖
- 注解配置相对分散,使用Java Config可以集中管理配置
- 可以在编译时进行依赖检查,不容易出错
1.2.2、缺点
与xml配置文件相比,可维护性差
2、相关注解
- @Configuration:描述类,用于标记Java Config配置类
- @Bean:描述方法,IOC容器会管理被标记方法返回的对象(bean id默认为方法名)
- @ComponentScan:描述类,扫描指定类中的注解配置(作用与xml配置中的context:component-scan标签相同)
- @ImportResource:描述类,加载静态文件,可使用@Value注解获取
| 由于是Java类的形式,所以同样可以使用各种类注解,比如@Primary
3、使用步骤
3.1、创建配置类
- 需要使用 @Configuration 注解标注配置类
//JavaConfig.java
package spring.config;
import org.springframework.context.annotation.Configuration;
@Configuration
public class JavaConfig {
}
3.2、创建bean
StudentController类
//StudentController.java
package spring.controller;
import lombok.Data;
import spring.service.StudentService;
@Data
public class StudentController {
private StudentService service;
public StudentController() {
System.out.println("StudentController创建");
}
}
StudentService类
//StudentService.java
package spring.service;
public class StudentService {
public StudentService() {
System.out.println("StudentService创建");
}
}
创建bean
- 使用@Bean注解标注方法,IOC容器管理方法返回的对象(与XML配置中的标签作用相同)
- bean id为方法名
//JavaConfig.java
package spring;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import spring.controller.StudentController;
import spring.service.StudentService;
@Configuration
public class JavaConfig {
//此处创建service、controller两个bean
@Bean
public StudentService service() {
StudentService service = new StudentService();
return service;
}
@Bean
public StudentController controller() {
StudentController controller = new StudentController();
return controller;
}
}
测试
测试类
//ApplicationContext.java
package spring;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
import spring.config.JavaConfig;
import spring.controller.StudentController;
import java.util.Arrays;
public class ApplicationContext {
public static void main(String[] args) {
AbstractApplicationContext context = new AnnotationConfigApplicationContext(JavaConfig.class);
String[] beanDefinitionNames = context.getBeanDefinitionNames();
Arrays.stream(beanDefinitionNames).forEach(e -> System.out.println(e));
}
}
测试结果
| 打印IOC容器中所有的bean
观察到两个bean创建成功
3.3、设置对象依赖
- 设置对象依赖时,将依赖的对象通过方法的属性传入,并在方法中通过构造方法、setter等方式注入依赖
- 在查找属性对应的bean时,先按属性名查找,找不到再按属性类型查找
//JavaConfig.java
......
@Bean
public StudentController controller(StudentService service) {
StudentController controller = new StudentController();
controller.setService(service);
return controller;
}
测试
测试结果
| 打印controller
观察到属性注入成功