如何为springbeanid添加前缀?

mw3dktmi  于 2021-07-15  发布在  Java
关注(0)|答案(0)|浏览(477)

我想为spring-config.xml中的大多数bean添加前缀,但不是所有bean。前缀值在属性文件中。问题是当我得到bean时,${prefix}不起作用。
spring-config-beans.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <import resource="spring-config-beans.xml"/>
</beans>

spring-config-beans.xml文件

<?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:jsf="http://jsf.jd.com/schema/jsf"
       default-lazy-init="true" default-autowire="byName"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://jsf.jd.com/schema/jsf http://jsf.jd.com/schema/jsf/jsf.xsd">

    <!-- I want to bean id will be "asdfStudentBean",now it can't work -->
    <bean id="`${myprefix}`StudentBean"
          class="com.example.beans.StudentBean">
        <property name="name" value="${myprefix}" /> 
        <!-- if beanid is "asdfStudentBean" then it can work, the name will be "asdf" -->
    </bean>

</beans>

应用程序属性

myprefix=asdf

studentbean.java文件

public class StudentBean {
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void printName() {
        System.out.println("your name is : " + this.name);
    }
}

测试代码

@SpringBootTest
class Demo3ApplicationTests {
    @Autowired
    private ApplicationContext applicationContext;

    @Test
    void contextLoads(){
        StudentBean bean = (StudentBean) applicationContext.getBean("asdfStudentBean");
        bean.printName();
    }

}
<bean id="${myprefix}StudentBean"    [FAIL]
<bean id="`${myprefix}`StudentBean"  [FAIL]
<bean id="@@myprefix@@StudentBean"   [FAIL]
<bean id="$${myprefix}StudentBean"   [FAIL]

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题