【问题标题】:about spring boot Profile can not work关于spring boot Profile不能工作
【发布时间】:2017-05-18 12:02:33
【问题描述】:

当我使用命令时

mvn spring-boot:run -Dspring.profiles.active=web

我的项目正在运行,但@Profile("web") bean 代码未使用,仅使用 bean 编写的属性

 @Profile("default")

如何更改它,并将属性更改为网络配置文件?

@Profile("default")
@Bean
static public PropertySourcesPlaceholderConfigurer defaultPropertySourcesPlaceholderConfigurer() {
    PropertySourcesPlaceholderConfigurer p = new PropertySourcesPlaceholderConfigurer();
    Resource[] resourceLocations = new Resource[] { new ClassPathResource("job.core.properties") };
    p.setLocations(resourceLocations);
    return p;
}

@Profile("web")
@Bean
static public PropertySourcesPlaceholderConfigurer prodWebPropertySourcesPlaceholderConfigurer() {
    PropertySourcesPlaceholderConfigurer p = new PropertySourcesPlaceholderConfigurer();
    Resource[] resourceLocations = new Resource[] {new ClassPathResource("job.core.ris.properties") };
    p.setLocations(resourceLocations);
    return p;
}

job.core.ris.properties

db.driverClass=com.mysql.jdbc.Driver
db.jdbcUrl=jdbc:mysql://192.168.0.68:3306/job_ris?rewriteBatchedStatements=true&useUnicode=true&characterEncoding=UTF-8
db.user=root
db.password=

job.core.properties

db.driverClass=com.mysql.jdbc.Driver
db.jdbcUrl=jdbc:mysql://192.168.0.68:3306/dev?rewriteBatchedStatements=true&useUnicode=true&characterEncoding=UTF-8

当我使用动作时,显示这个

【问题讨论】:

  • 为什么@Bean 注解的方法是静态的?尝试删除static
  • 如果删除静态 jdbcUrl 将为空

标签: spring maven spring-boot profiles


【解决方案1】:

使用框架而不是反对/围绕它。 Spring Boot 有 build in support 来加载配置文件特定的 application.properties 文件。

而不是试图将多个PropertyPlaceholderConfigurer 硬塞到 Spring Boot 应用程序中。创建包含您的属性的 application.propertiesapplication-web.properties

application.properties

db.driverClass=com.mysql.jdbc.Driver
db.jdbcUrl=jdbc:mysql://192.168.0.68:3306/dev?rewriteBatchedStatements=true&useUnicode=true&characterEncoding=UTF-8

application-web.properties

db.jdbcUrl=jdbc:mysql://192.168.0.68:3306/job_ris?rewriteBatchedStatements=true&useUnicode=true&characterEncoding=UTF-8
db.user=root
db.password=

(请注意缺少的db.driverClass,您只需要包含不同的属性)。

接下来删除您自定义的 @Bean 注释方法,让 Spring Boot 完成繁重的工作。

专业提示:从属性名称来看,您还有一个自定义 @Bean 用于您的 DataSource。您可能希望使用 spring.datasource.* 属性并让 Spring Boot 创建/管理您的数据源,而不是使用自定义名称。

【讨论】:

  • 好的,我以前用过这个方法,就可以了。永远感谢。
猜你喜欢
  • 2017-02-28
  • 2017-03-23
  • 2021-12-31
  • 1970-01-01
  • 1970-01-01
  • 2018-12-24
  • 2019-04-30
  • 2017-12-21
相关资源
最近更新 更多