1)获取框架中的bean
spring通过静态方法中传递ServletContext对象获得ApplicationContext,而后从ApplicationContext中获得相关bean,如下示例。这样使得调用者必须依赖HttpServletRequest,很难做出无参的静态工具方法。
private static synchronized void init(HttpServletRequest request) {
Map<String, Object> beans = WebApplicationContextUtils
.getRequiredWebApplicationContext(
request.getSession().getServletContext())
.getBeansWithAnnotation(Service.class);
seam在框架中通过threadLocal封装了各种上下文,可以直接通过无参静态代码获得,非常便于使用.
Commponent.getInstace(beanName)
spring也可以通过实现ApplicationContextAware接口,服务启动时自动创建实例,并将ApplicationContext设置到实例的静态属性中,这样就能静态获取ApplicationContext
@Component
public class SpringBeanUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext; // Spring应用上下文环境
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
SpringBeanUtil.applicationContext = applicationContext;
}
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
更新中。。。。。