mox601 mox601 - 10 days ago 5
Java Question

refer bean defined in another .xml

I have 2 spring application context 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" />


The file A.xml is not under my control, so I can't import B.xml with
<import resource="classpath*:B.xml" />
, but B.xml imports A.xml, so it's all the other way around.

The aBean is consistently instantiated with the bBean as null, due to the permissive
SpEL
syntax
#{getObject('bBean')}
.

Is there a way to overcome this?

Thanks!

Answer

This works:

Main class:

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


    }
}

Class 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();
    }
}

Class 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>