Spring全局获取Bean实例对象
2018-01-26 21:33
645 查看
在使用maven做接口的时候发现一个问题,maven不能出现循环依赖,否则编译报错,那么如果业务逻辑中不得不循环依赖时怎么办呢?
Spring在服务启动的时候会自动加载bean实例,而且用容器管理,虽然一个项目可能依赖于其他父项目 或者 子项目,但是最终都会被编译成同一个项目,那么bean最终也就是在同一个容器中管理,此时可以借助于容器,绕过maven的循环依赖,直接从容器中获取响应的bean实例,代码如下
代码实例
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
public class SpringContextHelper implements ApplicationContextAware {
private static ApplicationContext context = null;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.context = applicationContext;
}
public static Object getBean(String name) {
return context.getBean(name);
}
public static Object getBean(Class<?> c) {
return context.getBean(c);
}
}
Spring在服务启动的时候会自动加载bean实例,而且用容器管理,虽然一个项目可能依赖于其他父项目 或者 子项目,但是最终都会被编译成同一个项目,那么bean最终也就是在同一个容器中管理,此时可以借助于容器,绕过maven的循环依赖,直接从容器中获取响应的bean实例,代码如下
代码实例
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
public class SpringContextHelper implements ApplicationContextAware {
private static ApplicationContext context = null;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.context = applicationContext;
}
public static Object getBean(String name) {
return context.getBean(name);
}
public static Object getBean(Class<?> c) {
return context.getBean(c);
}
}
相关文章推荐
- spring 从bean实例中获取对象
- 获取Spring IOC容器代理的Bean实例的几种方式
- 在服务器启动时servlet中获取spring 的bean对象
- 在servlet中获取spring Bean对象
- Spring3.1.0实现原理分析(八).获取bean对象
- Struts 2在Action中获取Spring容器中所有Bean实例名称的方法
- spring学习(五)ClassPathXmlApplicationContext的getBean获取实例bean
- 获取Spring容器中Bean实例的工具类(Java泛型方法实现)
- S2SH框架中,Spring通过注解获取bean实例
- Web容器中获取spring容器的bean对象
- 获取Spring容器中Bean实例的工具类(Java泛型方法实现)
- Spring启动后获取所有拥有特定注解的Bean实例代码
- JavaWeb项目获取Spring自动装配的Bean对象
- 获取Spring的Bean持有容器对象的方法
- 【Spring】手动获取spring容器对象时,报no qualifying bean of type is defined
- Spring3.1.0实现原理分析(八).获取bean对象
- bean的加载(四)从bean的实例中获取对象
- 使用SpringContextHolder获取bean实例
- spring获取bean实例
- 自定义SpringContextHolder获取bean实例