SpringBoot自动装配

SpringBoot自动装配

昨天学习了Spring框架的手动装配,今天来看下SpringBoot的自动化装配。

定义:基于约定大于配置的原则,实现Spring组件自动装配的目的

底层装配技术:

  • Spring模式注解装配
  • Spring@Enable模块装配
  • Spring条件装配
  • Spring工厂加载机制
    • 实现类:SpringFactoriesLoader
    • 配置资源:META-INF/spring.factories

实现方式:

  • 激活自动装配
  • 实现自动装配
  • 配置自动装配实现

自定义自动装配

  1. 激活自动装配

在昨天的工程中的bootstrap包中新建一个EnableAutoConfigurationBootstrap

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package cn.myjdemo.springbootlearning.bootstrap;


import org.springframework.boot.WebApplicationType;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.ConfigurableApplicationContext;

@EnableAutoConfiguration
public class EnableAutoConfigurationBootstrap {

public static void main(String[] args) {
ConfigurableApplicationContext context = new SpringApplicationBuilder(EnableAutoConfigurationBootstrap.class)
.web(WebApplicationType.NONE)
.run(args);

//关闭上下文
context.close();
}
}
  1. 实现自动装配

configuration包中新建一个HelloWorldAutoConfiguration

1
2
3
4
5
6
7
8
9
10
11
12
package cn.myjdemo.springbootlearning.configuration;

import cn.myjdemo.springbootlearning.annotation.EnableHelloWorld;
import cn.myjdemo.springbootlearning.condition.ConditionalOnSystemProperty;
import org.springframework.context.annotation.Configuration;

@Configuration //Spring模式注解
@EnableHelloWorld //Spring@Enable模块装配
@ConditionalOnSystemProperty(name = "user.name",value = "Administrator") //条件装配
public class HelloWorldAutoConfiguration {

}
  • 条件判断: user.name == "Administrator"
  • 模式注解: @Configuration
  • @Enable 模块: @EnableHelloWorld -> HelloWorldImportSelector -> HelloWorldConfiguration - > helloWorld
  1. 配置自动装配实现

在项目的resources目录下新建一个文件夹META-INF,在里面新建一个spring.factories文件

1
2
3
# 自动装配
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
cn.myjdemo.springbootlearning.configuration.HelloWorldAutoConfiguration

然后在EnableAutoConfigurationBootstrap检验helloWorld Bean是否加载

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package cn.myjdemo.springbootlearning.bootstrap;


import org.springframework.boot.WebApplicationType;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.ConfigurableApplicationContext;

@EnableAutoConfiguration
public class EnableAutoConfigurationBootstrap {

public static void main(String[] args) {
ConfigurableApplicationContext context = new SpringApplicationBuilder(EnableAutoConfigurationBootstrap.class)
.web(WebApplicationType.NONE)
.run(args);

//helloWorld是否存在
String helloWorld = context.getBean("helloWorld",String.class);

System.out.println(helloWorld);

//关闭上下文
context.close();
}
}

运行后发现helloWorld加载成功

因此可以看出SpringBoot自动装配是在Spring框架的手动装配基础上发展而来的

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×