参考另一个.xml中定义的bean



我有2个弹簧应用程序上下文xmls:

a.xml

<bean id="aBean" class="...">
    <constructor-arg name="..." ref="..."/>
    <constructor-arg name="bBean" value="#{getObject('bBean')}"/>
</bean>

b.xml

 <bean id="bBean" class="...">
    ...
 </bean>
<import resource="classpath*:A.xml" />

文件a.xml不在我的控制之下,因此我无法用 <import resource="classpath*:B.xml" />导入b.xml,而是b.xml导入a.xml,所以相反,这是。

由于允许的SpEL语法#{getObject('bBean')},ABEAN始终将BBEAN作为null实例化。

有没有办法克服这一点?

谢谢!

这有效:

主类

package com.example;
import com.example.route.A;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.ImportResource;

@SpringBootApplication
@ImportResource(locations = {"classpath*:/ctxt/B.xml"})
public class DemoApplication {

    public static void main(String[] args) {
        ApplicationContext ctxt = SpringApplication.run(DemoApplication.class, args);
        A a = ctxt.getBean(A.class);
        System.out.println(a.toString());   // A{b=com.example.route.B@5488b5c5}   <-- A init correctly with non-null B

    }
}

类A

package com.example.route;
public class A {
    private B b;
    public A(B b) {
        this.b = b;
    }
    public B getB() {
        return b;
    }
    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder("A{");
        sb.append("b=").append(b);
        sb.append('}');
        return sb.toString();
    }
}

类B

package com.example.route;
public class B {
}

/resources/ctxt/a.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">
    <bean id="aBean" class="com.example.route.A">
        <constructor-arg name="bBean" value="#getObject('bBean')"/>
    </bean>
</beans>

/resources/ctxt/b.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">
    <bean id="bBean" class="com.example.route.B"></bean>
    <import resource="classpath*:ctxt/A.xml"></import>
</beans>

最新更新