2016-11-30 38 views
1

我有2首弹簧的应用上下文定义的个XML豆:指在另一个的.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不是下我的控制,所以我不能导入B.xml与<import resource="classpath*:B.xml" />,但B.xml导入A.xml,所以这是另一回事。

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

有没有办法解决这个问题?

谢谢!

回答

0

这工作:

Main类

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{[email protected]} <-- 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> 
+0

该项目正常工作。然而,我最终得到了另一个文件A.xml,其中我定义了bBean,以便在类路径中找到的名为A.xml的2个文件合并为一个。在我的项目不起作用,可能是由于加载整个依赖关系树的xml的奇怪方式,其中包括〜100个模块。 – mox601

+0

如果它不适用于你的大项目,请检查你的classpath。如果你正在创建一个大的jar文件,打开它并查看这个xml文件在哪里,很可能你没有在你的“classpath *:”字符串文字定义中正确引用它。 – dimitrisli

+0

Classpath应该没问题,因为A.xml位于A.jar的根级别,包含在B中作为第二级别依赖关系,如下所示:B - >(other module) - > A。使用intellij idea spring plugin并点击' classpath *:A.xml“/>'正确解析到该文件。 – mox601

相关问题