如何将Bean注入到普通类中
Spring管理的类获得一个注入的Bean方式
@Autowired是一种注解,可以对成员变量、方法和构造函数进行标注,来完成自动装配的工作,自动执行当前方法,如果方法有参数,会在IOC容器中自动寻找同类型参数为其传值。
如Controller中注入Bean可以这么写:
- @RestController
- public class TestController {
- @Autowired
- public TestBean bean;// 配置文件bean
- }
非Spring管理的类获得一个注入的Bean方式
上述通过@Autowired注解注入的方式只可以用在Spring管理的类中,而普通类中通过这样的方式获得的Bean为null。
可以使用Spring上下文ApplicationContext获得Bean的方式,将Bean注入到普通类中
普通类中通过ApplicationContext上下文获得Bean
- public class Test{
- //声明要注入的Bean变量
- private static TestBean bean;
- // 通过applicationContext上下文获取Bean
-
- public static void setApplicationContext(ApplicationContext applicationContext) {
- bean = applicationContext.getBean(TestBean.class);
- }
- }
修改SpringBoot启动类
将ApplicationContext传入普通类中
- @SpringBootApplication
- public class TestrApplication {
- public static void main(String[] args) {
- final ApplicationContext applicationContext = SpringApplication.run(TestApplication.class, args);
- // 将上下文传入Test类中,用于检测tcp连接是否正常
- Test.setApplicationContext(applicationContext);
- }
- }
这样一个Spring的Bean就可以注入到普通类中使用了.
在普通类中如何获取Bean节点
- /*
- * 文件名:SpringContextUtil.java
- * 描述:获取bean实例工具类
- * 修改人:Wang Chinda
- * 修改时间:2018/10/30
- * 修改内容:新增
- */
- package com.chinda.utils;
- import org.springframework.beans.BeansException;
- import org.springframework.context.ApplicationContext;
- import org.springframework.context.ApplicationContextAware;
- import org.springframework.stereotype.Component;
- /**
- * 获取bean实例工具类
- * @author Wang Chinda
- * @date 2018/10/30
- * @see
- * @since 1.0
- */
- @Component
- public class SpringContextUtil implements ApplicationContextAware {
- /**
- * 上下文对象实例
- */
- private static ApplicationContext applicationContext;
- @Override
- public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
- this.applicationContext = applicationContext;
- }
- /**
- * 获取applicationContext
- *
- * @return
- */
- public static ApplicationContext getApplicationContext() {
- return applicationContext;
- }
- /**
- * 通过name获取Bean.
- *
- * @param name
- * @return
- */
- public static Object getBean(String name) {
- return getApplicationContext().getBean(name);
- }
- /**
- * 通过class获取Bean.
- *
- * @param clazz
- * @param <T>
- * @return
- */
- public static <T> T getBean(Class<T> clazz) {
- return getApplicationContext().getBean(clazz);
- }
- /**
- * 通过name以及Class返回指定的Bean
- *
- * @param name
- * @param clazz
- * @param <T>
- * @return
- */
- public static <T> T getBean(String name, Class<T> clazz) {
- return getApplicationContext().getBean(name, clazz);
- }
- }
以上为个人经验,希望能给大家一个参考,也希望大家多多支持w3xue。