JavaConfig 原来是 Spring 的一个子项目,它通过 Java 类的方式提供 Bean 的定义信息,在 Spring4 的版本, JavaConfig 已正式成为 Spring4 的核心功能 。

官方文档:https://docs.spring.io/spring/docs/5.2.3.RELEASE/spring-framework-reference/

编写一个实体类,Dog

1
2
3
4
@Component  //将这个类标注为Spring的一个组件,放到容器中!
public class Dog {
public String name = "dog";
}

新建一个config配置包,编写一个MyConfig配置类

1
2
3
4
5
6
7
8
9
@Configuration  //代表这是一个配置类
public class MyConfig {

@Bean //通过方法注册一个bean,这里的返回值就Bean的类型,方法名就是bean的id!
public Dog dog(){
return new Dog();
}

}

测试

1
2
3
4
5
6
7
@Test
public void test2(){
ApplicationContext applicationContext =
new AnnotationConfigApplicationContext(MyConfig.class);
Dog dog = (Dog) applicationContext.getBean("dog");
System.out.println(dog.name);
}

导入其他配置如何做呢

我们再编写一个配置类

1
2
3
@Configuration  //代表这是一个配置类
public class MyConfig2 {
}

在之前的配置类中我们来选择导入这个配置类

1
2
3
4
5
6
7
8
9
@Configuration
@Import(MyConfig2.class) //导入合并其他配置类,类似于配置文件中的 inculde 标签
public class MyConfig {

@Bean
public Dog dog(){
return new Dog();
}
}

image-20200116213417021