有什么方法可以解析 beanName 中的占位符吗?

Is there any way to resolve placeholder in beanName?

<?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>

当我使用这样的配置时,Spring 将使用 beanName ${custom.beanName} 创建 BeanDefinition,并且不会解析其中的占位符。 但是我想使用在custom.properties文件中声明的beanName,有什么办法可以达到这个要求吗?

尝试从上下文中获取 bean 时,以下配置将导致 NoSuchBeanDefinitionException

<bean class="com.wqh.demo.TestBean" name="${custom.beanName}" />

但是,XML 属性名称的模板提案显示如下

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

基于此,以下解决方法是可行的

考虑到属性文件条目是:

custom.beanName=propBeanName

提供多个别名的bean配置如下

<bean class="com.wqh.demo.TestBean" name="testBeanName ${custom.beanName}"  />

现在当您getBean()基于应用程序上下文中的名称时,它会成功检索 bean

示例代码

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);
}

将在控制台中显示以下内容

[propBeanName]
com.wqh.demo.TestBean@4c60d6e9