之前,我们讲过一个普通的pojo如何被Spring纳管,请参考:好玩Spring之FactoryBean。
现在,我们有个需求,如何在一个普通的pojo中,调用spring bean的方法,比如以下例子。
service
@Service
public class TestService2 {
public String test1() {
return "11";
}
}
Task
public class Task {
TestService2 service2 = SpringUtils.getBean("testService2");
public String test() {
return service2.test2();
}
}
在以上的Task类中,我们想调用Service中的方法,但是Task不受Spring管理,如何获取Service呢?
其实方式有很多,更多的是,先获取ApplicationContext,再通过ApplicationContext的getBean(beanName)方法来获取bean。
关于如何获取ApplicationContext,参考好玩Spring之获取ApplicationContext的几种方式。
今天我们用BeanFactoryPostProcessor来实现获取bean的效果,话不多说,直接上代码。
@Component
public final class SpringUtils implements BeanFactoryPostProcessor {
private static ConfigurableListableBeanFactory beanFactory;
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
SpringUtils.beanFactory = beanFactory;
}
public static <T> T getBean(String name) throws BeansException {
return (T) beanFactory.getBean(name);
}
}
以上方式,可以在容器启动后,通过名称来获取bean,进而实现在普通Java类中调用bean的方法。
So easy。
更多BeanFactoryPostProcessor的用法参考之前的文章 好玩Spring之BeanFactoryPostProcessor