我在@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/