Issue
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<context:component-scan base-package="com.wqh">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
<context:exclude-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice"/>
</context:component-scan>
<bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:custom.properties</value>
</list>
</property>
</bean>
<aop:aspectj-autoproxy proxy-target-class="true"/>
<bean class="com.wqh.demo.TestBean" name="${custom.beanName}" />
</beans>
When I use configuration like this, Spring will create BeanDefinition with beanName ${custom.beanName}
, and will not resolve the placeholder inside it.
But I want to use the beanName which declared in custom.properties
file, is there any way to achieve this requirement?
Solution
The following configuration would result in NoSuchBeanDefinitionException
when attempting to get the bean from context.
<bean class="com.wqh.demo.TestBean" name="${custom.beanName}" />
However , the XML Template Proposals for attribute name shows the following
Attribute : name Can be used to create one or more aliases illegal in an (XML) id. Multiple aliases can be separated by any number of spaces, commas, or semi-colons (or indeed any mixture of the three).
Data Type : string
Based on this , the following work around is possible
Considering the properties file entry is :
custom.beanName=propBeanName
Provide the bean configuration with multiple alias names as follows
<bean class="com.wqh.demo.TestBean" name="testBeanName ${custom.beanName}" />
Now when you getBean()
based on the name from the application context , it would retrieve the bean successfully
Sample code
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("app-context.xml");
System.out.println(Arrays.asList(ctx.getAliases("testBeanName")));
TestBean bean = (TestBean)ctx.getBean("propBeanName");
System.out.println(bean);
}
would display the following in the console
[propBeanName]
com.wqh.demo.TestBean@4c60d6e9
Answered By - R.G
Answer Checked By - David Goodson (JavaFixing Volunteer)