Reading 2 property files having the same variable names in Spring

I am reading property files using the following entry in my Spring xml.

<context:property-placeholder 
    location="classpath:resources/database1.properties,
              classpath:resources/licence.properties"/>

I entered these values ​​into a variable using an xml entry, or using annotation @Value.

<bean id="myClass" class="MyClass">
    <property name="driverClassName" value="${database.driver}" />
    <property name="url" value="${database.url}" />
    <property name="name" value="${database.name}" />
</bean>

I want to add a new properties file ( database2.properties) that has several identical variable names, such as database1.properties.

database1.properties:

database.driver=com.mysql.jdbc.Driver
database.url=jdbc:mysql://192.168.1.10/
database.name=dbname

database2.properties:

database.url=jdbc:mysql://192.168.1.50/
database.name=anotherdbname
database.user=sampleuser

You can see that several property variables have the same name, for example database.url, database.namein property files.

Can I database.urlenter2.properties from the database?

Or do I need to change variable names?

Thank.

+4
3

, PropertyPlaceholderConfigurer. , , , placeholderPrefix, , -

<bean id="firstPropertyGroup" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
  <property name="locations" value="classpath:resources/database1.properties,
              classpath:resources/licence.properties" />
   <property name="placeholderPrefix" value="${db1."/>
</bean>

<bean id="secondPropertyGroup" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
  <property name="locations" value="classpath:resources/database2.properties" />
  <property name="placeholderPrefix" value="${db2."/>"
</bean>

, ${db1.database.url} ${db2.database.url}

+3

, , . : . , , , , .   ( ).

+3

You will sooner or later switch to Spring Boot. So with Spring Boot you can have a POJO like this:

public class Database {

  @NotBlank
  private String driver;
  @NotBlank
  private String url;
  @NotBlank
  private String dbname;

  public String getDriver() {
    return driver;
  }
  public void setDriver(String driver) {
    this.driver = driver;
  }
  public String getUrl() {
    return url;
  }
  public void setUrl(String url) {
    this.url = url;
  }
  public String getDbname() {
    return dbname;
  }
  public void setDbname(String dbname) {
    this.dbname = dbname;
  }
}

and use @ConfigurationProperties to populate it:

@Bean
@ConfigurationProperties(locations="classpath:database1.properties", prefix="driver")
public Database database1(){
  return new Database();
}

@Bean
@ConfigurationProperties(locations="classpath:database2.properties", prefix="driver")
public Database database2(){
  return new Database();
}

The disadvantage of this is that it is modified. Using Lombok , you can eliminate nasty getters and setters.

+2
source

All Articles