Spring bean instance order

I ran into a problem in which the sequence of the Bean sequence is important. Currently, Bean3 below performs a database-based caching operation and Bean 1 requests a newly created cache using Proxy Bean2. The priority is that Bean3 and Bean 2 must be fully created before Bean1 receives an instance, i.e. When the Spring container appears. These beans are in a separate JARS, and the Bean2 link in Bean1 does not use Autowired. Instead, the service locator gives it a link. We use Spring 2.5.2 and do not use XML to instantiate beans. Any help appreciated!

  • JAR1 Project (Spring)

    @Service ("bean3") public class Bean3 implements ApplicationListener { public void onApplicationEvent() { //load data from DB and populate cache } public void getCache(){ //get data from cache } 

    }

     @Service ("bean2") public class Bean2 { @Autowired private Bean3 bean3; private void methodA(){ bean3.getCache(); } } 
  • JAR2 project (not Spring)

     public class Bean1{ Bean2 bean2 = SpringServiceLocator.getBean("bean2") public void methodB(){ bean2.methodA(); } } 
+7
source share
2 answers

If I understand correctly, you are trying to execute some logic when starting the application (init context).

If so, I would suggest using BeanPostProcessor to perform any special operations when the application starts.

 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; } } 

Remember to tell Spring about your mail processor

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

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

Hope this helps.

+1
source

Maybe your homegrown Spring Service Latitude needs a signal, as shown below

  Lock l = new ReentrantLock(); Condition springready = l.newCondition(); l.lock(); try { while (READY_FLAG) springready.await(); ... } finally { l.unlock(); } 

additionally

you can listen to ContextRefreshedEvent to change READY_FLAG and the "springready" signal

0
source

All Articles