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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With