Record several ways to obtain spring container objects
1. BeanFactoryAware interface
/**
* 获取spring容器的方式-实现BeanFactoryAware
* @Author:lzf
* @Date: 2023-3-17
*/
@Service
public class UserService implements BeanFactoryAware {
private BeanFactory beanFactory;
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
this.beanFactory = beanFactory;
}
public void test(){
User user = beanFactory.getBean(User.class);
System.out.println(user);
}
}
2. ApplicationContextAware interface
/**
* 获取spring容器的方式-实现ApplicationContextAware
*
* @Author:lzf
* @Date: 2023-3-17
*/
@Service
public class UserService1 implements ApplicationContextAware {
private ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
public void test(){
User user = (User) applicationContext.getBean("user");
System.out.println(user);
}
}
3. ApplicationListener interface
Note that the generic type received by this interface is ContextRefreshedEvent
a class.
/**
* 获取spring容器的方式-实现ApplicationListener
* @Author:lzf
* @Date: 2023-3-17
*/
@Service
public class UserService2 implements ApplicationListener<ContextRefreshedEvent> {
private ApplicationContext applicationContext;
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
applicationContext = event.getApplicationContext();
}
public void test(){
User user = applicationContext .getBean(User.class);
System.out.println(user);
}
}