手写自动配置,加载到springboot中
【摘要】 1. 创建自动配置类@Configuration // 让spring知道这个是配置类@ConditionalOnClass(MyService.class) // 仅在 MyService 存在时启用@EnableConfigurationProperties(MyServiceProperties.class) // 启用配置绑定public class MyServiceAutoCon...
1. 创建自动配置类
@Configuration // 让spring知道这个是配置类
@ConditionalOnClass(MyService.class) // 仅在 MyService 存在时启用
@EnableConfigurationProperties(MyServiceProperties.class) // 启用配置绑定
public class MyServiceAutoConfiguration {
@Bean
@ConditionalOnMissingBean // 如果用户未手动定义 MyService,则自动创建
public MyService myService(MyServiceProperties properties) {
return new MyService(properties.getName(), properties.getTimeout());
}
}
2. 创建 @ConfigurationProperties
绑定类
@ConfigurationProperties(prefix = "my.service") // 配置的属性前缀以my.service开头
public class MyServiceProperties {
private String name = "defaultService";
private int timeout = 5000;
// Getter & Setter 省略
}
@ConfigurationProperties
会自动配置需要读取 application.properties
或 application.yml
配置,prefix = "my.service"
会绑定 application.properties
中的 my.service
配置项
my:
service:
name: "CustomService"
timeout: 3000
Spring Boot 会自动加载这些参数,并传递给 MyServiceAutoConfiguration
。
3. 注册自动配置到 spring.factories
Spring Boot 通过 META-INF/spring.factories
机制发现并加载自定义的自动配置类。
在 src/main/resources/META-INF/spring.factories 添加:
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.example.config.MyServiceAutoConfiguration
这样,Spring Boot 在启动时就会自动加载自定义的配置。
4. 测试自动配置
直接在 @SpringBootApplication
入口类中注入 MyService
@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
@Bean
CommandLineRunner runner(MyService myService) {
return args -> System.out.println("MyService Name: " + myService.getName());
}
}
application.yml 中配置了 my.service.name=CustomService,所以效果为控制台打印: MyService Name: CustomService。 自动配置已成功生效!
【声明】本内容来自华为云开发者社区博主,不代表华为云及华为云开发者社区的观点和立场。转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息,否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)