资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

【Spring】普通类获取Spring容器的bean的方法-创新互联

我们通常在项目中获取Spring容器里bean的方式,一般是使用注解的方式(@Autowired、@Resource)直接注入就可以直接使用了,那么如果在一个普通的类里(其他地方使用它的实例是以new的方式使用的),此时再用注解的方式注入的将会是null,那这种情况下,我们该如何使用Spring容器里的bean呢?本篇博客讲解五种方法,接下来就依次详细讲一下使用方式

创新互联建站专注于武安企业网站建设,成都响应式网站建设公司,购物商城网站建设。武安网站建设公司,为武安等地区提供建站服务。全流程按需定制设计,专业设计,全程项目跟踪,创新互联建站专业和态度为您提供的服务一、在初始化时保存ApplicationContext对象
FileSystemXmlApplicationContext fileSystemXmlApplicationContext = new FileSystemXmlApplicationContext("applicationContext.xml");
// 1、使用类名获取
XXX xxx = SpringContextService.getBean(XXX.class);
// 2、使用bean名获取
Object yyy = SpringContextService.getBean("beanName");
二、通过Spring提供的工具类获取ApplicationContext对象
WebApplicationContext requiredWebApplicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);

WebApplicationContext webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(servletContext);
// 1、使用类名获取
XXX xxx = SpringContextService.getBean(XXX.class);
// 2、使用bean名获取
Object yyy = SpringContextService.getBean("beanName");
三、继承自抽象类ApplicationObjectSupport
public class SpringTest extends ApplicationObjectSupport {private void test(){// 1、使用类名获取
        XXX xxx = getApplicationContext().getBean(XXX.class);
        // 2、使用bean名获取
        Object yyy = getApplicationContext().getBean("beanName");

    }
}
四、继承自抽象类WebApplicationObjectSupport
```java
public class SpringTest extends WebApplicationObjectSupport{private void test(){// 1、使用类名获取
        XXX xxx = getApplicationContext().getBean(XXX.class);
        // 2、使用bean名获取
        Object yyy = getApplicationContext().getBean("beanName");

    }
}
五、实现接口ApplicationContextAware

实现该接口的setApplicationContext(ApplicationContext context)方法,并保存ApplicationContext 对象。
Spring初始化时,会通过该方法将ApplicationContext对象注入
1、添加一个类,实现ApplicationContextAware

@Component
public class SpringContextService implements ApplicationContextAware {private static ApplicationContext applicationContext;
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {if (SpringContextService.applicationContext == null) {SpringContextService.applicationContext = applicationContext;
        }
    }

    public staticT getBean(Classclazz) {return applicationContext.getBean(clazz);
    }
    public static Object getBean(String beanName) {return applicationContext.getBean(beanName);
    }
}

2、普通类的实际使用

// 1、使用类名获取
XXX xxx = SpringContextService.getBean(XXX.class);
// 2、使用bean名获取
Object yyy = SpringContextService.getBean("beanName");

以上就是普通类获取Spring容器的bean的几种方法,感谢您的阅读!

你是否还在寻找稳定的海外服务器提供商?创新互联www.cdcxhl.cn海外机房具备T级流量清洗系统配攻击溯源,准确流量调度确保服务器高可用性,企业级服务器适合批量采购,新人活动首月15元起,快前往官网查看详情吧


分享文章:【Spring】普通类获取Spring容器的bean的方法-创新互联
路径分享:http://cdkjz.cn/article/dhiepd.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

大客户专线   成都:13518219792   座机:028-86922220