SpringBoot中如何获取Spring容器对象?


在日常开发中,我们经常需要从Spring容器中获取bean,但你知道如何获取Spring容器对象吗?

1、BeanFactoryAware接口:

@Service
public class PersonService implements BeanFactoryAware {
    private BeanFactory beanFactory;

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        this.beanFactory = beanFactory;
    }

    public void add() {
        Person person = (Person) beanFactory.getBean("person");
    }
}

实现BeanFactoryAware接口,然后重写setBeanFactory方法,你就可以从该方法中获得spring容器对象。

2、ApplicationContextAware 接口:

@Service
public class PersonService2 implements ApplicationContextAware {
    private ApplicationContext applicationContext;

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

    public void add() {
        Person person = (Person) applicationContext.getBean("person");
    }
}

实现ApplicationContextAware接口,然后重写setApplicationContext方法,你也可以从这个方法中获得spring容器对象。

3、ApplicationListener 

@Service
public class PersonService3 implements ApplicationListener<ContextRefreshedEvent> {
    private ApplicationContext applicationContext;
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        applicationContext = event.getApplicationContext();
    }

    public void add() {
        Person person = (Person) applicationContext.getBean("person");
    }
}