Springboot自动配置的运行原理(自定义一个自动配置)

1.新建一个空的maven项目,在pom中导入

<dependency>

<groupId>junit</groupId>

<artifactId>junit</artifactId>

<version>4.11</version>

<scope>test</scope>

</dependency>

<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-autoconfigure -->

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-autoconfigure</artifactId>

<version>2.0.4.RELEASE</version>

</dependency>

 

2.新建一个类型安全的取值类,可以自动获取application.properties或application.yml的值

@ConfigurationProperties(prefix = "hello")

public class HelloServicesProperties {

 

private static final String MSG = "world";

 

//这儿是类型安全的属性填充值,在application中通过hello.msg=来设置,若不设置,默认为hello.msg=world

private String msg = MSG;

 

public String getMsg() {

return msg;

}

 

public void setMsg(String msg) {

this.msg = msg;

}

}

 

3.新建一个判断依据类,根据此类的存在与否来创建这个类的Bean,这个类可以是第三方类库的类。在调用该包使用时,即根据此类来调用相应的方法,此类中会包含有application中传递的值。

public class HelloService {

private String msg;

 

public String sayHello(){

return "Hello " + msg;

}

 

public String getMsg() {

return msg;

}

 

public void setMsg(String msg) {

this.msg = msg;

}

}

 

4.新建自动配置类,会根据条件判断是否自动创建HelloService类。根据HelloServiceProperties提供的参数,并通过@ConditionalOnClass判断HelloService个类在类路径中是否存在,且当容器中没有这个Bean的情况下自动配置这个Bean。

@Configuration

@EnableConfigurationProperties(HelloServicesProperties.class)

@ConditionalOnClass(HelloService.class)

@ConditionalOnProperty(prefix = "hello",value = "enabled",matchIfMissing = true)

public class HelloServiceAutoConfiguration {

 

@Autowired

private HelloServicesProperties helloServicesProperties;

 

@Bean

@ConditionalOnMissingBean(HelloService.class)

public HelloService helloService(){

HelloService helloService = new HelloService();

helloService.setMsg(helloServicesProperties.getMsg());

return helloService;

}

}

 

5.新建一个Model来使用上面自定义的自动配置:创建Module方式很简单,选中上面的Project右键单击,New一个Module,这个Module是一个SpringBoot项目,创建成功之后选择新建的Module按F4打开Module设置,然后选择右边的加号添加依赖,如下:

 

 

 

6.在新建Model的pom中引入自定义的自动配置

<dependency>

<groupId>com.wisely</groupId>

<artifactId>spring-boot-starter-hello</artifactId>

<version>1.0-SNAPSHOT</version>

</dependency>

 

7.在Model的入口类中编写一个控制来测试我们自定义的自动配置

@RestController

@SpringBootApplication

public class TestAutoApplication {

 

@Autowired

private HelloService helloService;

 

@RequestMapping("/")

public String index(){

return helloService.sayHello()+" 测试自动配置";

}

 

public static void main(String[] args) {

 

SpringApplication.run(TestAutoApplication.class, args);

}

}

 

8.此时启动后可以在浏览器输入:localhost:8080来访问,默认没有写配置文件时,显示:

 

9.可以通过application.properties中修改配置来配置,如:hello.msg=xjf,此时访问显示为: