【问题标题】:Spring Inject java.util.Properties or Map from @PropertySource via @ValueSpring 通过@Value 从@PropertySource 注入java.util.Properties 或Map
【发布时间】:2014-09-15 07:18:11
【问题描述】:

我在@Configuration 类中有以下内容

@PropertySource(name = "applicationProperties", value = {
        "classpath:application.properties",
        "classpath:${spring.profiles.active}.properties",
        "classpath:hibernate.properties",
"classpath:${spring.profiles.active}.hibernate.properties" })

我想以 java.util.Properties 对象的形式检索所有属性,或者使用 @Value 通过前缀将其过滤为属性子集。

//This works but only gives System.properties
@Value("#{systemProperties}")
private Properties systemProperties;

//I want to do this, but I can't find a way to make it work with Spring EL if there is a way.
@Value("#{application.Properties}")
private Properties appProperties;

我使用的是纯 java 配置,我只需要以某种方式获取由 @PropertySource 配置的属性。 Spring Environment 一次只允许您获取一个属性。

简而言之,我真正想要的是所有以hibernate为前缀的属性。*

【问题讨论】:

    标签: java spring


    【解决方案1】:

    请看以下链接:

    http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html

    如果您正在或可以使用 Spring Boot,那么您可以执行以下操作:

    @Component
    @ConfigurationProperties(locations = "classpath:config/hibernate.properties", prefix = "hibernate")
    public class HibernateProperties {
    
        Properties datasource = new Properties();
    
        public Properties getDatasource() {
            return datasource;
        }
    
    }
    

    还有 hibernate.properties 文件:

    hibernate.datasource.initialize=false
    hibernate.datasource.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver
    hibernate.datasource.url=jdbc:sqlserver://xxx;DatabaseName=yyy
    hibernate.datasource.username=user
    hibernate.datasource.password=passwd
    

    看到 hibernate 是前缀,datasource 是属性对象的名称。所以你可以调用像 datasource.get("initialize") 这样的属性。

    你可以在任何地方注入 HibernateProperties 类并调用 getProperties 方法来获取休眠属性。 希望这会有所帮助。

    【讨论】:

    • 不是我想要的,因为我无法将 HibernateSettings 对象传递给采用 Properties 对象的方法...
    猜你喜欢
    • 1970-01-01
    • 2015-08-21
    • 1970-01-01
    • 1970-01-01
    • 2017-01-15
    • 2014-12-22
    • 2014-10-03
    • 1970-01-01
    相关资源
    最近更新 更多