SpringBoot手动获取Bean类

版权声明:个人博客:blog.suyeq.com 欢迎访问 https://blog.csdn.net/hackersuye/article/details/88060726

一般在多线程的环境中,bean类的获取不能通过自动装载来获取到,spring会认为其不安全,也就是不能用@Autowired注解来获取bean类。

这时候需要来在Spring中来手动获取bean类。

  • 需要继承实现ApplicationContextAware接口
@Component
public class BeanFactoryTest implements ApplicationContextAware {

    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext=applicationContext;
    }

    public ApplicationContext getApplicationContext() {
        return applicationContext;
    }
}

该接口下setApplicationContext方法是需要实现的,该方法将spring的applicationContext引用赋值给自定义的applicationContext

获取对应的bean类实现如下:

 BlogService blogService=beanFactoryTest.getApplicationContext().getBean(BlogService.class);

猜你喜欢

转载自blog.csdn.net/hackersuye/article/details/88060726