你好,我是leo。在上篇文章中,我写了一个spring boot autoconfiguration 的最简例子。
实际应用场景下,还会根据各种条件进一步增强自动装配的控制逻辑。
常见的条件注解有:
名称 | 说明 |
---|---|
@EnableAutoConfiguration | 用于启用Spring Boot的自动配置机制。使用@SpringBootApplication注解时默认开启自动配置 |
@ConditionalOnClass | 当类路径中存在特定类时,才会生效配置。可以用于决定是否需要自动配置特定类的Bean。 |
@ConditionalOnBean | 当Spring容器中存在特定Bean时,才会生效配置。用于基于Bean的存在与否来决定配置是否生效。 |
@ConditionalOnProperty | 当指定的配置属性满足特定条件时,才会生效配置。可以根据属性的值来决定是否应用配置。 |
@ConditionalOnMissingBean | 当Spring容器中不存在特定Bean时,才会生效配置。用于防止覆盖用户自定义的Bean。 |
@AutoConfigureBefore和@AutoConfigureAfter | 用于控制自动配置类的加载顺序,可确保配置的先后顺序。 |
@ConfigurationProperties | 将外部配置属性绑定到Java类,用于在自动配置类中配置属性。 |
spring boot提供的这些注解,可以根据条件、属性和依赖来决定如何自动配置,它们有助于在不同情况下实现灵活的自动配置机制。
那么,leo就在上一篇文章代码的基础上,给自动装配扩展自定义属性功能。
首先定义一个属性model类HelloProperties
@ConfigurationProperties(prefix = "hello")
@Data
public class HelloProperties {
private String name = "null";
private String desc = "null";
}
@ConfigurationProperties(prefix = “hello”)表示会读取application.yaml中以hello开头的配置项,并将配置的key-value映射到name属性和desc属性。注意,这个yaml文件可以是实现自动装配的框架类的yaml,也可以是引用这个框架的其他项目的yaml配置文件。
其次,定义框架类的接口和实现:
public interface HelloService {
String getInfo();
}
public class HelloServiceImpl implements HelloService {
private HelloProperties properties;
public HelloServiceImpl(HelloProperties properties){
this.properties=properties;
}
@Override
public String getInfo() {
return properties.getName()+" "+ properties.getDesc();
}
}
接下来,在自动装配的时候启用@EnableConfigurationProperties
@Configuration
@EnableConfigurationProperties(value = HelloProperties.class)
public class HelloServiceAutoconfiguration2
{
@Autowired
HelloProperties helloProperties;
@Bean
@ConditionalOnMissingBean(HelloService.class)
public HelloService helloService(){
HelloService helloService = new HelloServiceImpl(helloProperties);
return helloService;
}
}
最后,在/resource/META-INF/spring.factories文件中加入配置
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.example.common.service.HelloServiceAutoconfiguration2
autoconfiguration的功能就完成了,可以部署到maven给其他项目使用了。
那么使用方如果在yaml配置文件中有如下配置:
hello:
name: leo
desc: autoconfiguration demo
最终调用HelloService.getInfo方法就会得到结果“leo autoconfiguration demo”
好了,实现一个spring boot starter系列文章到这里就结束了。