美文网首页
Spring boot自定义配置

Spring boot自定义配置

作者: 我是腿哥 | 来源:发表于2017-05-15 17:48 被阅读0次

示例

db.demo.enable=true

添加maven依赖项

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>

该依赖可以解决配置文件中,名称高亮的问题.

设置配置

@ConditionalOnProperty(value = "db.demo.enable", havingValue = "true")
@Configuration
public class DbAutoConfiguration {

    @Primary
    @Bean(initMethod = "init", destroyMethod = "close")
    @ConfigurationProperties(prefix = "db.demo")
    public DruidDataSource dataSource() {
        return new DruidDataSource();
    }
}
  • 代码第一行@ConditionalOnProperty设置是否开启该名称下,db.demo自定义注解.在配置文件中需要加入该配置且要其值为true,例如:db.demo.enable=true.
  • 在配置类中要加入@Configuration注解
  • @Primary注解的介绍.在spring 中使用注解,常使用@Autowired, 默认是根据类型Type来自动注入的。但有些特殊情况,对同一个接口,可能会有几种不同的实现类,而默认只会采取其中一种的情况下 @Primary 的作用就出来了。
  • @ConfigurationProperties(prefix = "db.demo")是定义配置名称.

IDE配置

image.png

需要开启注解模式.

相关文章

网友评论

      本文标题:Spring boot自定义配置

      本文链接:https://www.haomeiwen.com/subject/dgbhxxtx.html