1. 获取spring容器的bean对象 我们日常工作中,经常需要获取spring容器的bean对象,大家知道如何获取嘛?1.1 实现ApplicationContextAware接口获取spring bean
@Service public class TianLuoService implements ApplicationContextAware { private ApplicationContext context; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { context = applicationContext; } //炒田螺 public void friedTianLuo() { TianLuo tianluo = (TianLuo) applicationContext.getBean("tianluo"); tianluo.fried(); } }
这个比较常用,其实就是实现ApplicationContextAware接口,然后在setApplicationContext方法中设置一下Spring的ApplicationContext实例,就可以获取啦~~1.2 实现BeanFactoryAware接口获取spring bean我们还可以实现BeanFactoryAware接口,然后在setBeanFactory方法中设置一下Spring的BeanFactory实例,就可以通过spring的Bean工厂类获取到对应的bean~~
@Service public class TianLuoService implements BeanFactoryAware { private BeanFactory beanFactory; @Override public void setBeanFactory(BeanFactory beanFactory) throws BeansException { this.beanFactory = beanFactory; } //炒田螺 public void friedTianLuo() { TianLuo tianluo = (TianLuo) beanFactory.getBean("tianluo"); tianluo.fried(); } }
但是实际开发中,我们一般通过实现ApplicationContextAware接口的方式来获取spring容器中的Bean~~
地址:https://mp.weixin.qq.com/s/T9LM_zgRwvk7Ktc6HBqozQ
标签:15,beanFactory,spring,tianluo,获取,bean,开发,public From: https://www.cnblogs.com/jelly12345/p/18623770