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就可以注入到普通类中使用了.


如有错误请指正!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

banmajio

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值