我有2个spring应用程序上下文XML:
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。
有没有办法克服这个问题?
谢谢!
答案 0 :(得分:0)
这有效:
主要课程:
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>