Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to inject complete propertiesfile in a springbean

I have a properties-file with a lot of values and I do not want to list them in my bean-configuration-file separately. E.g.:

<property name="foo">
    <value>${foo}</value>
</property>
<property name="bar">
    <value>${bar}</value>
</property>

and so on.

I imagine to inject all completely as java.util.Properties or less as a java.util.Map. Is there a way to do so?

like image 964
Jan Avatar asked May 09 '11 15:05

Jan


People also ask

How do you inject a properties file?

Here we read the properties file data and after reading the data inject it into the required bean or class and by using the expression we can read the IOC context data. 1- Load properties file data into IOC context scope. 2- Inject context scope data into required bean/class.

How property values can be injected directly into your beans in Spring Boot?

Property values can be injected directly into your beans using the @Value annotation, accessed via Spring's Environment abstraction or bound to structured objects via @ConfigurationProperties . Spring Boot uses a very particular PropertySource order that is designed to allow sensible overriding of values.

How do you inject properties in Java?

To successfully inject properties in Java EE, you need the @Produces annotation which allows the injection of primitives (such as int, long, float…). You cannot also inject classes such as String or Date because these classes are packaged in the rt. jar file which is missing a beans.


1 Answers

For Java config you can use something like this:

@Autowired @Qualifier("myProperties")
private Properties myProps;

@Bean(name="myProperties")
public Properties getMyProperties() throws IOException {
    return PropertiesLoaderUtils.loadProperties(
        new ClassPathResource("/myProperties.properties"));
}

You can also have multiple properties this way, if you assign a unique bean name (Qualifier) to each instance.

like image 84
rustyx Avatar answered Sep 23 '22 15:09

rustyx