Shrihastha
Shrihastha

Reputation: 71

PropertiesFactoryBean vs @PropertySource

I need to read menu.properties file only in the class MyServiceImpl.java These values are not Environment specific.

menu.properties
----------------
menu.option=option1,option2,option3

1)using @PropertySource

@Configuration
@ComponentScan(basePackages = { "com.test.*" })
@PropertySource("classpath:menu.properties")
public class MyServiceImpl{

    @Autowired
    private Environment env;
    public List<String> createMenu(){
       String menuItems = env.getProperty("menu.option");
...}
}

2) How to access the below bean in MyServiceImpl.java

<bean id="properties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
    <property name="location" value="classpath:menu.properties"/>
</bean>

Which approach do I need to follow and what is the difference between PropertiesFactoryBean and PropertySource?

Upvotes: 1

Views: 5035

Answers (1)

minion
minion

Reputation: 4353

Use of Environment: Environment provides convenient interface for providing property sources. The properties can be loaded from jvm args, system variables, property file etc. Using env provides better abstraction IMHO.

Given a choice i would prefer Environment as it provides better abstraction. Instead of properties files you can load from jvm arguments or system variables tomorrow, the interface is going to remain the same.

To answer you second question (I have provided short form as well).

Long form:

<bean id="properties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
    <property name="location" value="classpath:menu.properties"/>
</bean>

Short form:

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

public class MyServiceImpl{

    @Autowired
    private Properties properties;
    public List<String> createMenu(){
       String menuItems = properties.getProperty("menu.option");
...}
}

Third option

If you going to read properties directly and if there are not environment specific, i would suggest using <context:property-placeholder> which registers PropertySourcesPlaceholderConfigurer.

<context:property-placeholder location="classpath:menu.properties" />

if you declare as above, you can directly read values using @value annotation as below.

public class MyServiceImpl{

    @value("${menu.option}")
    String menuItems;

    public List<String> createMenu(){
       //use items directly;
...}

}

Upvotes: 2

Related Questions