一.自动配置
所谓自动配置,就是Spring容器启动后,一些配置类、bean对象就自动存入了IOC容器当中,而不需要我们手动声明,直接从IOC容器中引入即可。省去了繁琐的配置操作。
我们可以首先将spring项目启动起来,里面有一项
里面有一项beans
点击application
里面列出了我们当前spring项目中IOC容器里所有的bean对象。我们可以看到有CommonConfig,里面有个bean对象reader,
这与我们的代码一致,类型是SAXReader,也一致。
我们发现还有一个CommonConfig类,里面也有一个bean对象commonConfig,为什么还有一个这个bean对象呢?我们可以打开@Configuration注解。
发现其就是基于@Component注解的,因此这个配置类也是spring的IOC容器的一部分。
还有我们自己定义的bean
除了我们自己定义的类,这里还有spring自动生成的配置类,比如有一个配置类叫GsonAutoConfiguration,里面有一个bean对象gson。类型也是Gson。这个bean是Google当中提供的,用来处理json格式的数据,如果我们想使用,直接使用@Autowired注入进来即可。
我们准备一个单元测试类:
package com.itheima;
import org.springframework.boot.test.context.SpringBootTest;
/**
* 自动配置原理测试
*/
@SpringBootTest
public class AutoConfigurationTests {
@AutoWired
private Gson gson;
@Test
public void TestJson() {
String json = gson.toJson(Result.success());
System.out.println(json);
}
}