Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

<util:properties> equivalent in java based configuration for spring

Tags:

java

spring

What would be the equivalent in java based configuration of XML based spring configuration

<util:properties id="mapper"  location="classpath:mapper.properties" /> 

To then be able to use this specific property object in code like :

@Resource(name = "mapper") private Properties myTranslator; 

Looking at the doc, I looked at the

@PropertySource 

annotation but it seems to me that the particular propertyfile will not be able to be accessed individually from the Environment object.

like image 894
Yves Nicolas Avatar asked Sep 19 '13 13:09

Yves Nicolas


People also ask

How do you inject Java Util properties into Spring beans?

Spring Bean + Properties + Annotation configuration example Create a configuration class and define the properties bean in it as shown below. Create a spring bean class and inject properties into it using @Autowired and @Qualifier annotations. Create main class and run application.

What is Java Util properties?

The java.util.Properties class is a class which represents a persistent set of properties.The Properties can be saved to a stream or loaded from a stream.Following are the important points about Properties − Each key and its corresponding value in the property list is a string.

What is Spring configuration file in Java?

A Spring configuration file is an XML file that contains the classes information. It describes how those classes are configured as well as introduced to each other. The XML configuration files, however, are verbose and cleaner.

Which attributes are required for property tag in XML based Spring configuration?

In XMLbased configuration metadata, you use the id and/or name attributes to specify the bean identifier(s). This attribute specifies the scope of the objects created from a particular bean definition and it will be discussed in bean scopes chapter.


1 Answers

Very simply, declare a PropertiesFactoryBean.

@Bean(name = "mapper") public PropertiesFactoryBean mapper() {     PropertiesFactoryBean bean = new PropertiesFactoryBean();     bean.setLocation(new ClassPathResource("com/foo/jdbc-production.properties"));     return bean; } 

In the documentation here, you'll notice that before they made <util:properties>, they used to use a PropertiesFactoryBean as such

<!-- creates a java.util.Properties instance with values loaded from the supplied location --> <bean id="jdbcConfiguration" class="org.springframework.beans.factory.config.PropertiesFactoryBean">   <property name="location" value="classpath:com/foo/jdbc-production.properties"/> </bean> 

Converting that to Java config is super easy as shown above.

like image 170
Sotirios Delimanolis Avatar answered Sep 24 '22 06:09

Sotirios Delimanolis