AKSM
AKSM

Reputation: 327

Spring bean instantiation ordering

I have run into an issue where Bean instantiation sequencing matters. Currently Bean3 from below is running a DB based cache put operation, and Bean 1 queries against the newly created cache using Proxy Bean2. Priority is for Bean3 and Bean 2 to be completely instantiated before Bean1 gets instantiated, i.e. when Spring container comes up. These beans are in seperate JARS, and Bean2 reference into Bean1 is not using Autowired. Instead a service locator is giving it a reference. We are using Spring 2.5.2 and not using XML for instantiation of beans. Any help appreciated!

Upvotes: 7

Views: 3428

Answers (2)

sashok_bg
sashok_bg

Reputation: 2971

If I understand correctly, you are trying to perform some logic on application startup (context init).

If this is the case, I would suggest that you use BeanPostProcessor, to perform any special operations at application startup.

public class MyBeanPostProcessor implements BeanPostProcessor {

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName)
            throws BeansException {

        .. **perform special things**
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName)
            throws BeansException {
        ..**perform special things**
        return bean;
    }
}

Do not forget to tell Spring about your post processor

<context:component-scan base-package="some.package" />
<bean class="some.package.MyBeanPostProcessor"

For more info read here http://static.springsource.org/spring/docs/3.0.0.M3/reference/html/ch04s07.html

I hope this helps.

Upvotes: 1

farmer1992
farmer1992

Reputation: 8156

maybe your homegrew Spring Service locator need a signal like below

        Lock l = new ReentrantLock();
        Condition springready = l.newCondition();

        l.lock();
        try {
          while (READY_FLAG)
              springready.await();

            ...

        } finally {
          l.unlock();
        }

in addition

you can listen ContextRefreshedEvent to change READY_FLAG and signal 'springready'

Upvotes: 0

Related Questions