Jay Mie
Jay Mie

Reputation: 65

Retrieving property/value as string from Spring bean

I have the following in my context.xml:

<bean id="myBean" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
        <list>
            <value>file:${specific.dir}/file1.properties</value>
            <value>file:${specific.dir}/file2.properties</value>
            <value>file:${specific.dir}/file3.properties</value>
            <value>file:${specific.dir}/file4.properties</value>
        </list>
    </property>
</bean>

I am retrieving this bean in a POJO through a static spring application context, and going through the debugger this does seem to work.

Is there anyway for me to retrieve the four values in the list, and the property name in this POJO?

my staticSpringApplicationContext is as follows :

public class StaticSpringApplicationContext implements ApplicationContextAware  {
private static ApplicationContext CONTEXT;

  public void setApplicationContext(ApplicationContext context) throws BeansException {
    CONTEXT = context;
  }

  public static Object getBean(String beanName) {
    return CONTEXT.getBean(beanName);
  }

}

and following this in my POJO I have:

StaticSpringApplicationContext.getBean("myBean");

Any help or guidance is greatly appreciated. I have had more trouble with Spring than I care to admit.

Upvotes: 0

Views: 1587

Answers (2)

onexdrk
onexdrk

Reputation: 121

You can use spring @Value annotation, smth like this:

@Component
public MyClass {

  @Value("${some.prop.name1}")
  private String myProp1;

}

file1.properties:

some.prop.name1=value1

I hope it will be helpful. Good luck.

Upvotes: 1

Jim Garrison
Jim Garrison

Reputation: 86774

Whether you can do this will depend on the bean definition. It must have a setLocations() method (or be correctly annotated) via which Spring will inject the values.

You would retrieve the values using a getter method on the bean if one exists. If not you will need to modify the bean.

Upvotes: 0

Related Questions