java - Spring 通过@Value 从@PropertySource 注入(inject)java.util.Properties 或Map

标签 java spring

我在@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 环境一次只允许您获取一个属性。

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

最佳答案

请看下面的链接:

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") 之类的属性。

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

关于java - Spring 通过@Value 从@PropertySource 注入(inject)java.util.Properties 或Map,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24921781/

相关文章:

java - 在 vaadin 和 spring 下进行日志记录

java - 热敏打印机仅在设置断点时打印

java - log4j 通过 System.out.println

java - 连接到用户输入数据库

spring - 为具有 2 个不同登录门户的同一应用程序在同一浏览器上维护不同的 session ID

java - JPQL 构造函数忽略具有 NULL 值的行

java - 如何防止注册 Activity 重复录入

java - 使用连接构造函数创建的套接字的连接超时是多少?

Spring Security - 基本 HTTP 身份验证 - 更改服务器消息

java - 如何在 Heroku 中运行 Spring Boot WAR 应用程序?