AutoConfiguration
Spring-boot的一个重要特性就是提供了各种各样的AutoConfiguration。例如DataSourceAutoConfiguration。这样我们只需要在配置文件中进行如下配置
spring:
datasource:
url: jdbc:mysql://xxxxxxxxxxx/realname
username: xxxxx
password: xxxxx
driverClassName: com.mysql.jdbc.Driver
Spring-Boot就会在容器中按照我们的配置的信息注入一个DataSource。那么Spring boot是怎么知道 DataSourceAutoConfiguration是自动配置类?其实很简单:
1. spring boot 在启动时候会读取文件Classpath:\META-INF\spring.factories的所有文件,spring.factories其实是一个properties的文件,即是 key = value的形式。
2. 获取spring.factories中key=org.springframework.boot.autoconfigure.EnableAutoConfiguration配置项的值(类的全路径)作为Spring启动配置类
Spring Boot 这种用“约定优于配置”思想可以大大的简化配置代码的编写。那么,我们就可以按照上面的套路来编写一个Spring-Boot的自动配置类吧
实战
现在有一个配置Bean——PrintAfterInitBean,需要Spring容器启动以后,打印一次消息,并且该消息的内容是在配置文件中定义
第一步,编写配置Bean——PrintAfterInitBean
代码如下,因为只是一个简单例子,这里的配置Bean其实可以是其他任何复杂配置Bean,例如DataSource。往往一个公共包需要多个这样配置Bean才能完成其配置。
public class PrintAfterInitBean implements InitializingBean {
private String message;
public void afterPropertiesSet() t