spring-boot 读取配置文件(多个yml)问题

在学习spring-boot的时候(这里是集成mybatis+druid的时候),由于单个yml配置文件写的配置太多,显的冗余了,于是将其分开配置。

然而,在做druid数据库配置信息加载的时候发现,相关的参数读取不到(这里很确认在分离前是能读取到的),然后定位可能是读取的机制,默认是application.yml文件。这个问题其实在之前曾经遇到过,只是一下子没想到。这里提供几个多文件数据读取的方式。

1.选择需要读取的额外配置文件(application.yml这个不需要)@PropertySource和@Value,如下图

@Configuration
    @PropertySource("classpath:application-datasource.yml")
    class IDataSourceProperties {
	@Value("${url}")
        private String url;
        @Value("${username}")
        private String username;
		********以下省略*********
	}

2.通过Environment获取

启动的时候加载所有需要的配置

@SpringBootApplication
@PropertySource("classpath:application.yml")
@PropertySource("classpath:application-datasource.yml")
@PropertySource("classpath:application-druid.yml")
public class IndexApplication {
    private  static Logger logger = Logger.getLogger(IndexApplication.class);

    @RequestMapping("/")
    String home() {
        return "Hello World!";
    }
    public static void main(String[] args) throws Exception{
        SpringApplication.run(IndexApplication.class, args);
        logger.info("======spring boot start success ===========");
    }

    @Bean
    public PropertySourcesPlaceholderConfigurer getSources() {
        return new PropertySourcesPlaceholderConfigurer();
    }

    /*@Bean
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource druidDataSource() {
        return new DruidDataSource();
    }*/

}

使用的时候配置

@Configuration
@Slf4j
public class DruidConfig {
    @Autowired
    private Environment env;

    /**
     * 注册一个StatViewServlet 相当于在web.xml中声明了一个servlet
     */
    @Bean
    public ServletRegistrationBean<StatViewServlet> druidServlet()
    {
        ServletRegistrationBean<StatViewServlet> reg = new ServletRegistrationBean<StatViewServlet>();
        reg.setServlet(new StatViewServlet());
        reg.addUrlMappings("/monitor/druid/*");
        /** 白名单 */
        reg.addInitParameter("allow", env.getProperty("spring.druid.web-stat-filter.allow"));
        /** IP黑名单(共同存在时,deny优先于allow) */
        reg.addInitParameter("deny", env.getProperty("spring.druid.web-stat-filter.deny"));
        /** 是否能够重置数据 禁用HTML页面上的“Reset All”功能 */
        reg.addInitParameter("resetEnable", env.getProperty("spring.druid.web-stat-filter.resetEnable"));
        reg.addInitParameter("loginUsername", env.getProperty("spring.druid.web-stat-filter.loginUsername"));
        reg.addInitParameter("loginPassword", env.getProperty("spring.druid.web-stat-filter.loginPassword"));
        return reg;
    }
	*****以下省略截取部分****

转载于:https://my.oschina.net/MjShao/blog/2245151

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值