Spring properties configuration using @PropertySource

前端 未结 1 1889
野的像风
野的像风 2020-12-29 17:28

In the below Spring configuration class, I\'m loading app.properties file via @PropertySource and constructing 2 different DBCP data sources using the configurations from th

相关标签:
1条回答
  • 2020-12-29 18:12

    If you are using (or willing to use) Spring Boot then you can use the @ConfigurationProperties annotation.

    Here is an example from the Spring Boot source code:

    @ConfigurationProperties(prefix = "spring.activemq")
    public class ActiveMQProperties {
    
        private String brokerUrl = "tcp://localhost:61616";
    
        private boolean inMemory = true;
    
        private boolean pooled = false;
    
        private String user;
    
        private String password;
    
        // Will override brokerURL if inMemory is set to true
        public String getBrokerUrl() {
            if (this.inMemory) {
                return "vm://localhost";
            }
            return this.brokerUrl;
        }
    
        public void setBrokerUrl(String brokerUrl) {
            this.brokerUrl = brokerUrl;
        }
    
        public boolean isInMemory() {
            return this.inMemory;
        }
    
        public void setInMemory(boolean inMemory) {
            this.inMemory = inMemory;
        }
    
        public boolean isPooled() {
            return this.pooled;
        }
    
        public void setPooled(boolean pooled) {
            this.pooled = pooled;
        }
    
        public String getUser() {
            return this.user;
        }
    
        public void setUser(String user) {
            this.user = user;
        }
    
        public String getPassword() {
            return this.password;
        }
    
        public void setPassword(String password) {
            this.password = password;
        }
    
    }
    

    Effectively what this does is map the properties spring.activemq.* to their respective properties.

    Using the previous kind of code spares you from needed to use @Value on each field.

    For the specific DataSource example you are showing, Spring Boot as of version 1.1.0.M1 provides the DataSourceBuilder which build on @ConfigurationProperties and vastly simplifies the kind of configuration you are trying to achieve. See the documentation here

    In your case the code would be:

    @Bean
    @ConfigurationProperties(prefix="txn")
    public DataSource primaryDataSource() {
        return DataSourceBuilder.create().build();
    }
    
    @Bean
    @ConfigurationProperties(prefix="rpt")
    public DataSource secondaryDataSource() {
        return DataSourceBuilder.create().build();
    }
    
    0 讨论(0)
提交回复
热议问题