对于web项目,编程方式获取bean如下:
1 WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext(); 2 CrmHttpClientBuilder builder = (CrmHttpClientBuilder) wac.getBean("crmHttpClientBuilder");
但是对于应用类项目要如何获取呢?方式之一就是通过实现ApplicationContextAware接口。
1. 定义接口
1 public class SpringContextUtil implements ApplicationContextAware { 2 // Spring应用上下文环境 3 private static ApplicationContext applicationContext; 4 /** 5 * 实现ApplicationContextAware接口的回调方法,设置上下文环境 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. 在applicationContext里面定义bean;只有这样定义才可以在spring初始化加载的时候填充该类的applicationContext。
<bean id="springContextUtils" class="brave.SpringContextUtil" />
3. 使用
1 CrmTracingFactoryBean beanFactory = (CrmTracingFactoryBean) SpringContextUtil.getBean("tracing"); 2 beanFactory.setLocalServiceName("lorry-dubbo-good");