Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Inject java.util.Properties or Map from @PropertySource via @Value

Tags:

java

spring

I have the following in an @Configuration class

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

I want to retrieve all the properties as a java.util.Properties object or filter it to a subset of properties by prefix using @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;

I'm using a pure java configuration and I just need to get at the properties somehow that are configured by the @PropertySource. The Spring Environment only lets you get one property at a time.

In short, really what I want is all properties that are prefixed with hibernate.*

like image 884
chrislhardin Avatar asked Nov 28 '25 09:11

chrislhardin


1 Answers

Please see below link:

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

if you're, or can, use Spring Boot, than you can do something like this:

@Component
@ConfigurationProperties(locations = "classpath:config/hibernate.properties", prefix = "hibernate")
public class HibernateProperties {

    Properties datasource = new Properties();

    public Properties getDatasource() {
        return datasource;
    }

}

and the hibernate.properties file:

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

see that hibernate is prefix and datasource is the name of the properties object. so yo can call properties like datasource.get("initialize").

Than you can inject HibernateProperties class anywhere and call getProperties method to get the hibernate properties. Hope this helps.

like image 62
Gokhan Oner Avatar answered Nov 29 '25 22:11

Gokhan Oner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!