我有 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
,aBean 始终以 bBean 实例化为空。语法#{getObject('bBean')}
。
有办法克服这个问题吗?
谢谢!
最佳答案
这有效:
主类:
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>
关于java - 引用另一个 .xml 中定义的 bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40884107/