【问题标题】:Spring Boot multiple configurations files with same names and same properties namesSpring Boot 多个配置文件同名同属性名
【发布时间】:2018-07-07 11:17:30
【问题描述】:

我正在尝试设置一个 Spring Boot 单体应用程序,该应用程序的行为应该像一个微服务,但我在管理配置 (.properties) 时遇到了一些问题。 这就是我组织项目的方式(resources 文件夹):

如您所见,有一些常见的属性文件:application.propertiesapplication-dev.propertiesapplication-prod.properties 这些属性应该由所有子属性共享,并且最终可以被覆盖。

每个service 都有自己的数据源网址,它还取决于活动配置文件:H2 用于devMySQL 用于prod

这里是我如何管理配置的示例:

常见application.properties的内容:

spring.profiles.active=dev
spring.config.additional-location=classpath:productservice/, classpath:userservice/,classpath:financeservice/, classpath:securityservice/ #I am not sure this works...
spring.datasource.username=root
spring.datasource.password=root
spring.jpa.database=default
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=none 
spring.jpa.properties.validation-mode=none 

常见application-dev.properties的内容:

spring.datasource.driver-class-name=org.h2.Driver
spring.h2.console.enabled=true
spring.h2.console.path=/db
spring.h2.console.settings.trace=false
spring.h2.console.settings.web-allow-others=false
spring.datasource.username=sa # We override data source username and paswword
spring.datasource.password=
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect

常见application-prod.properties的内容:

spring.datasource.driver-class-name=com.mysql.jdbc.Driver

现在针对特定服务:

产品服务:

application.properties的内容:

spring.liquibase.change-log=classpath:productservice/db/changelog/db.changelog-master.xml
spring.liquibase.default-schema=productservicedb
spring.liquibase.check-change-log-location=true

application-dev.properties的内容:

spring.datasource.url=jdbc:h2:mem:productservicedb;DB_CLOSE_ON_EXIT=FALSE;INIT=CREATE SCHEMA IF NOT EXISTS productservicedb;MV_STORE=FALSE;MVCC=FALSE
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect

application-prod.properties的内容:

spring.datasource.url=jdbc:mysql://localhost:3306/productservicedb?useSSL=false

对于 userservice 我有:

application.properties的内容:

spring.liquibase.change-log=classpath:userservice/db/changelog/db.changelog-master.xml
spring.liquibase.default-schema=userservice
spring.liquibase.check-change-log-location=true

application-dev.properties的内容:

spring.datasource.url=jdbc:h2:mem:userservicedb;DB_CLOSE_ON_EXIT=FALSE;INIT=CREATE SCHEMA IF NOT EXISTS userservicedb;MV_STORE=FALSE;MVCC=FALSE
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect

application-prod.properties的内容:

spring.datasource.url=jdbc:mysql://localhost:3306/userservicedb

等等……其他服务。

要配置每个数据源,我会这样进行:

产品服务:

1- 从环境中检索属性:

@Configuration( "productServiceProperties" )
@Getter
@Setter
@PropertySource( value = { "classpath:productservice/application.properties",
  "classpath:productservice/application-${spring.profiles.active}.properties" } )
public class ProductServiceProperties {

   @Autowired//I want `Environment` to contain properties from common properties + files in @PropertySource above
   private Environment environment;

    // ========DATASOURCE PROPERTIES=========
   private String      datasourceDriverClass;
   private String      datasourceUsername;
   private String      dataSourcePassword;
   private String      dataSourceUrl;

   // ========LIQUIBASE PROPERTIES==========
   private String      liquibaseChangeLog;
   private String      liquibaseDefaultSchema;

   @PostConstruct
   public void init() {
      this.datasourceDriverClass = environment.getProperty( "spring.datasource.driver-class-name" );
      datasourceUsername = environment.getProperty( "spring.datasource.username" );
      dataSourcePassword = environment.getProperty( "spring.datasource.password" );
      dataSourceUrl = environment.getProperty( "spring.datasource.url" );

      liquibaseChangeLog = environment.getProperty( "spring.liquibase.change-log" );
      liquibaseDefaultSchema = environment.getProperty( "spring.liquibase.default-schema" );
      log.debug( "Initialisation {} ", datasourceDriverClass );
  }
}

2- 在数据库配置中注入它们:

@Configuration
@EnableJpaRepositories( basePackages = "com.company.product.repository", entityManagerFactoryRef = "productServiceEntityManager", transactionManagerRef = "productServiceTransactionManager", considerNestedRepositories = true )
@EnableTransactionManagement( proxyTargetClass = false )
public class ProductServiceDBConfig {

    private static final String      packageToScan = "com.company.product.models";

    @Autowired
    private ProductServiceProperties productServiceProperties;

    @Bean( name = "productServiceDataSource" )
    public DataSource productServiceDataSource() {
       DriverManagerDataSource dataSource = new DriverManagerDataSource();
       dataSource.setDriverClassName( productServiceProperties.getDatasourceDriverClass() );
       dataSource.setUrl( productServiceProperties.getDataSourceUrl() );
       dataSource.setUsername( productServiceProperties.getDatasourceUsername() );
       dataSource.setPassword( productServiceProperties.getDataSourcePassword() );
       return dataSource;
    }

   @Bean
public JpaVendorAdapter productServiceVendorAdapter() {
    HibernateJpaVendorAdapter hibernateJpaVendorAdapter = new HibernateJpaVendorAdapter();
    hibernateJpaVendorAdapter.setGenerateDdl( false );
    hibernateJpaVendorAdapter.setShowSql( true );
    return hibernateJpaVendorAdapter;
}

@Bean( name = "productServiceEntityManager" )
public LocalContainerEntityManagerFactoryBean productServiceEntityManager() {
    LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
    emf.setDataSource( productServiceDataSource() );
    emf.setPackagesToScan( packageToScan );
    emf.setJpaVendorAdapter( productServiceVendorAdapter() );
    return emf;
}

@Bean( name = "productServiceTransactionManager" )
public PlatformTransactionManager productServiceTransactionManager() {
    JpaTransactionManager productTransactionManager = new JpaTransactionManager();
    productTransactionManager.setEntityManagerFactory( productServiceEntityManager().getObject() );
    return productTransactionManager;
}

@Bean
public SpringLiquibase productServiceLiquibase() {
    SpringLiquibase liquibase = new SpringLiquibase();
    liquibase.setDataSource( productServiceDataSource() );
    liquibase.setChangeLog( productServiceProperties.getLiquibaseChangeLog() );
    liquibase.setDefaultSchema( productServiceProperties.getLiquibaseDefaultSchema() );
    return liquibase;
  }
}

用户服务:

1-

@Configuration( "userServiceProperties" )
@Getter
@Setter
@PropertySource( value = { "classpath:userservice/application.properties",
    "classpath:userservice/application-${spring.profiles.active}.properties" } ) //I want properties from properties file source above
public class UserServiceProperties {

    @Autowired //I want `Environment` to contain properties from common properties + files in @PropertySource above
    private Environment environment;

    // ========DATASOURCE PROPERTIES=========
    private String      datasourceDriverClass;
    private String      datasourceUsername;
    private String      dataSourcePassword;
    private String      dataSourceUrl;

    // ========LIQUIBASE PROPERTIES==========
    private String      liquibaseChangeLog;
    private String      liquibaseDefaultSchema;

    @PostConstruct
    public void init() {
        datasourceDriverClass = environment.getProperty( "spring.datasource.driver-class-name" );
        datasourceUsername = environment.getProperty( "spring.datasource.username" );
        dataSourcePassword = environment.getProperty( "spring.datasource.password" );
        dataSourceUrl = environment.getProperty( "spring.datasource.url" );

        liquibaseChangeLog = environment.getProperty( "spring.liquibase.change-log" );
        liquibaseDefaultSchema = environment.getProperty( "spring.liquibase.default-schema" );
    }
}

2-

@Configuration
@EnableJpaRepositories( basePackages = "com.company.user.repository", entityManagerFactoryRef = "userServiceEntityManager", transactionManagerRef = "userServiceTransactionManager", considerNestedRepositories = true )
@EnableTransactionManagement( proxyTargetClass = false )
public class UserServiceDBConfig {

private static final String         packageToScan = "com.company.user.models";

   @Autowired
   private UserServiceProperties userServiceProperties;

   @Bean( name = "userServiceDataSource" )
   public DataSource userServiceDataSource() {
      DriverManagerDataSource dataSource = new DriverManagerDataSource();
      dataSource.setDriverClassName( userServiceProperties.getDatasourceDriverClass() );
      dataSource.setUrl( userServiceProperties.getDataSourceUrl() );
      dataSource.setUsername( userServiceProperties.getDatasourceUsername() );
      dataSource.setPassword( userServiceProperties.getDataSourcePassword() );
      return dataSource;
  }

  @Bean
  public JpaVendorAdapter userServiceVendorAdapter() {
      HibernateJpaVendorAdapter hibernateJpaVendorAdapter = new HibernateJpaVendorAdapter();
      hibernateJpaVendorAdapter.setGenerateDdl( false );
      hibernateJpaVendorAdapter.setShowSql( true );
      return hibernateJpaVendorAdapter;
  }

  @Bean( name = "userServiceEntityManager" )
  public LocalContainerEntityManagerFactoryBean userServiceEntityManager() {
      LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
      emf.setDataSource( userServiceDataSource() );
      emf.setPackagesToScan( packageToScan );
      emf.setJpaVendorAdapter( userServiceVendorAdapter() );
      return emf;
  }

  @Bean( name = "userServiceTransactionManager" )
  public PlatformTransactionManager userServiceTransactionManager() {
      JpaTransactionManager userTransactionManager = new JpaTransactionManager();
      userTransactionManager.setEntityManagerFactory( userServiceEntityManager().getObject() );
      return userTransactionManager;
  }

  @Bean
  public SpringLiquibase userServiceLiquibase() {
      SpringLiquibase liquibase = new SpringLiquibase();
      liquibase.setDataSource( userServiceDataSource() );
      liquibase.setChangeLog( userServiceProperties.getLiquibaseChangeLog() );
      liquibase.setDefaultSchema( userServiceProperties.getLiquibaseDefaultSchema() );
      return liquibase;
   }
}

问题是,当我@Autowired Environment 获取我的属性并且所有属性都具有相同的名称时,某些属性总是优先于其他属性。例如。属性spring.datasource.url 在两个服务中包含相同的值。

我使用Environment 而不是@Value 也不是@ConfigurationProperties,因为它基于活动配置文件获取属性,而这正是我想要的。

我的问题是:

  • 是否可以配置Environment 以从注入它的配置类中获取属性?

  • 如果没有,有没有一种简单的方法可以实现我想做的事情?

  • 是否应该配置多个应用程序上下文(每个服务一个)以将每个 Environment 变量与其他变量隔离? (我不确定这是否可行)

非常感谢(很抱歉这篇文章太长了)

【问题讨论】:

    标签: java spring-mvc spring-boot properties configuration


    【解决方案1】:

    我根据 Twitter 上的 Andy Wilkinson (@ankinson) 的建议自己解决了这个问题。

    我们不能有许多同名的属性文件。所以我不得不像这样重命名我的子配置文件:

    product.properties
    product-dev.properties
    product-prod.properties
    

    等等……

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-28
      • 2015-01-16
      • 1970-01-01
      • 2017-12-21
      • 2021-11-27
      • 1970-01-01
      • 2021-04-06
      • 2023-03-24
      相关资源
      最近更新 更多