The application project gets the bean

  For web projects, programmatically get beans as follows:

1 WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext();
2 CrmHttpClientBuilder builder = (CrmHttpClientBuilder) wac.getBean("crmHttpClientBuilder");

  But how to get it for application projects? One way is by implementing the ApplicationContextAware interface.
  1. Define the interface

1  public  class SpringContextUtil implements ApplicationContextAware {    
 2      // Spring application context     
3      private  static ApplicationContext applicationContext;    
 4      /**   
5       * Implement the callback method of the ApplicationContextAware interface, set the context  
 6       *   
 7       * @param applicationContext  
 8       */     
9      public  void setApplicationContext (ApplicationContext applicationContext) {    
 10          SpringContextUtil.applicationContext = applicationContext;    
 11     }    
12     /**  
13      * @return ApplicationContext  
14      */    
15     public static ApplicationContext getApplicationContext() {    
16         return applicationContext;    
17     }
18     /**  
19      * 获取对象  
20      *   
21      * @param name  
22      * @return Object
23      * @throws BeansException  
24      */    
25     public static Object getBean(String name) throws BeansException {    
26         return applicationContext.getBean(name);
27     }    
28 }  

2. Define the bean in the applicationContext; only in this way can the applicationContext of the class be populated when spring is initialized and loaded.
 <bean id="springContextUtils" class ="brave.SpringContextUtil" />
3. Use

1 CrmTracingFactoryBean beanFactory = (CrmTracingFactoryBean) SpringContextUtil.getBean("tracing");
2 beanFactory.setLocalServiceName("lorry-dubbo-good");

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325519408&siteId=291194637