2016-11-30 20 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

相關問題