Issue
I have defined a bean in XML
like
<bean class="some.class.Clazz">
<property name="user" value="${user}"/>
</bean>
after that, I want to insert the value in java, I have the code like:
ConfigurableApplicationContext ctx = new ClassPathXmlApplicationContext("main.xml");
Properties ftpSessionProps = new Properties();
ftpSessionProps.setProperty("user", "first");
StandardEnvironment env = new StandardEnvironment();
env.getPropertySources().addLast(new PropertiesPropertySource("pops", ftpSessionProps));
ctx.setEnvironment(env);
ctx.refresh();
ctx.start();
But it never works...
and I tries to add
<context:property-placeholder />
in the xml
file, it gave me the logs:
Could not resolve placeholder 'user' in string value "${user}"
Any suggestions? Or recommendations for books or articles?
Thanks!
UPDATE
It seems that the class 'ConfigurableApplicationContext' can't be refreshed with the new env
. So we should be careful choosing the context
class. The one AbstractRefreshableConfigApplicationContext
could be refreshed and you should only initialize it with an empty resource. And set the configLocation
manually after you set the environment
.
Solution
The constructor with String
parameter automatically processes the file and fails because the environment hasn't been set yet.
You need to use zero-parameter constructor, call setConfigLocation
, setEnvironment
and then refresh
and start
:
AbstractRefreshableConfigApplicationContext ctx = new ClassPathXmlApplicationContext(); // init empty
Properties ftpSessionProps = new Properties();
ftpSessionProps.setProperty("user", "first");
StandardEnvironment env = new StandardEnvironment();
env.getPropertySources().addLast(new PropertiesPropertySource("pops", ftpSessionProps));
ctx.setEnvironment(env);
ctx.setConfigLocation("classpath:main.xml"); // set the config here
ctx.refresh();
ctx.start();
Answered By - Zbynek Vyskovsky - kvr000
Answer Checked By - Mary Flores (JavaFixing Volunteer)