SpringBoot 之 普通类获取Spring容器中的bean ,

难为一天多,终于解决,问题在于建造者模式下,引入另一个类时,此类中如下代码
@Autowired
ITdRecruitService iTdRecruitService;
//总是不成功,即获取不到 iTdRecruitService
建造者模式是什么,见下文
https://www.cnblogs.com/adamjwh/p/9033551.html
而我使用在在这样场景中被大连朋友告诉我是这个样子
SpringBoot 之 普通类获取Spring容器中的bean ,

 在如上RecruitPipline的类中,

通过@Autowired

 @Autowired
ITdRecruitService iTdRecruitService;
 //以下会 返回空指值,
iTdRecruitService.xxxx方法时()
 问题是注入不成功
 

问题本质:

解决了我的问题
进一步分析
之所以注入不成功

若类A中包含成员属性B, B是通过@Autowired自动注入,而类A的实例是通过new的方式产生,则自动注入会失效的。

哈哈哈,我犯的是这个错误。
 

解决方案文章如下

 

SpringBoot 之 普通类获取Spring容器中的bean ,解决  @Autowired 注解,拿下到bean问题

本文来源网址: https://funyan.cn/p/2869.html

我们知道如果我们要在一个类使用 spring 提供的bean对象,我们需要把这个类注入到spring容器中,交给spring容器进行管理,但是在实际当中,我们往往会碰到在一个普通的 Java 类中,想直接使用spring提供的其他对象或者说有一些不需要交给spring管理,但是需要用到spring里的一些对象。如果这是spring框架的独立应用程序,我们通过
ApplicationContext ac = new FileSystemXmlApplicationContext("applicationContext.xml");
ac.getBean("beanId"); 
这样的方式就可以很轻易的获取我们所需要的对象。
但是往往我们所做的都是Web Application,这时我们启动spring容器是通过在web.xml文件中配置,这样就不适合使用上面的方式在普通类去获取对象了,因为这样做就相当于加载了两次spring容器,而我们想是否可以通过在启动web服务器的时候,就把Application放在某一个类中,我们通过这个类在获取,这样就可以在普通类获取spring bean对象了。不多说,看实例!
1.在Spring Boot可以扫描的包下
写的工具类为SpringUtil,实现ApplicationContextAware接口,并加入Component注解,让spring扫描到该bean
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
/**
 * 普通类获取bean
 * @author lyq
 */
@Component
public class SpringUtil implements ApplicationContextAware {
	private static Logger logger = LoggerFactory.getLogger(SpringUtil.class);
	private static ApplicationContext applicationContext;	
	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		if(SpringUtil.applicationContext == null) {
			SpringUtil.applicationContext = applicationContext;
		}
		logger.info("ApplicationContext配置成功,applicationContext对象:"+SpringUtil.applicationContext);
	}
	public static ApplicationContext getApplicationContext() {
		return applicationContext;
	}
	public static Object getBean(String name) {
		return getApplicationContext().getBean(name);
	}
	public static <T> T getBean(Class<T> clazz) {
		return getApplicationContext().getBean(clazz);
	}
	public static <T> T getBean(String name,Class<T> clazz) {
		return getApplicationContext().getBean(name,clazz);
	}
}
2.调用方法
ProxyServiceImpl proxyService = SpringUtil.getBean(ProxyServiceImpl.class);
说明:这个获取bean的类需要先随者项目启动,也就是说,调用普通类的方法要放在SpringBoot的测试类或者是启动类下运行才能获取到ApplicationContext