Initialize Spring Bean as late as possible

I have a follofing situation int "super-context.xml":

<bean id="conf" class="ee.Conf"/>

<bean id="service" class="ee.Serivce">
  <property name="conf" ref="conf">
</bean>

Now I want to use this "super-context.xml" in various different projects. Say "sub-context.xml" has:

<import resource="super-context.xml"/>

<bean id="subConf1" class="ee.SubConf">
   <property name="confloc" value="classpath:ee/customconf1.sss" />
</bean>

<bean id="subConf2" class="ee.SubConf">
   <property name="confloc" value="classpath:ee/customconf2.sss" />
</bean>

...

<bean id="subConfn" class="ee.SubConf">
   <property name="confloc" value="classpath:ee/customconfn.sss" />
</bean>

ee.Conf is something as follows:

public class Conf ... {
    ...
    public void addSubConf(Resource res) {
       //configuration resolving from res
    }
    ...
} 

ee.SubConf is something as follows:

public class SubConf ... {
    ...
    @Autowired
    ee.Conf superConf;
    ...
    public void setConfloc(Resource res) {
       superConf.addSubConf(res);
    }
    ...
}

The problem aries on context load. Beans are initialized in following order (due to ordering in context file): conf, service, subConf1, subConf2, ... subConfn

But service bean actually depends on all the subConf beans (although this can't be deducted from the context definition itself). It loads OK when import in "sub-context.xml" is added after subConf bean definitions.

Reason behind this is implementing modularity. Is it possible to force a bean to load as late as possible ("service" bean in the example) or make beans of certain type load as soon as possible ("subConf" beans in the example), since fixed ordering of beans in "sub-context.xml" partly kills the wished modularity

Or is theree a more pure way to achieve this type of modularity?

Answers


I would say that you are approaching the problem in a wrong way. The SubConf shouldn't have a dependency on the Conf to start with. Simply inject the collection of SubConf objects in your Conf object.

public class Conf {

    @Autowired
    private List<SubConf> subconfs;
}

That way you eliminate the need for the SubConf to call the Conf class and this will remove your circular dependency.

See the Spring reference guide for more information on autowiring.


You can use depends-on

<bean id="beanOne" class="foo.Bar" depends-on="beanTwo" />

Need Your Help

how to prevent webpage layout destruction

html css layout

I have a webpage with the following layout: http://jsfiddle.net/h9Nn3/6/ and it looks exactly like I want it to as long as the user's browser is wide enough (over 700px or so) but if it is thinner ...