SpringBoot项目将Bean注入到普通类中
个人博客:banmajio’s blog
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就可以注入到普通类中使用了.
如有错误请指正!!