刚开始用rose,因为有些服务是在线程里的,需要getBean。
试了好几个办法,都没法得到spring的ApplicationContext,
比如实现 ApplicationContextAware 结果没Aware。
有一个解决办法是所有线程里用到的依赖都在new的时候传递进去(也是rose作者推荐的方案),不过有时候比较麻烦,比如依赖很多很多,参数一大串;或者临时测一下,又要写一堆@Autowired
另外wangqiaowqo(rose作者之一)在blog里写了通过 new RoseAppContext(); 的方法,实际使用发现这种方式相当于把spring又重启了一遍,所有服务都会重新init,有可能导致严重问题。
有没有办法实现类似一个App.getBean()这种方法呢。
我试了一下,是可以得到最初spring启动环境的那个ApplicationContext的,方法如下(有点绕哦,因为@Autowired不能注解static成员,就把app本身从ApplicationContext中getBean):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
/** * http://bianbian.org/890/paoding-rose-get-spring-applicationcontext/ */ @Component public class App implements InitializingBean { private static final Logger logger = LoggerFactory.getLogger(App.class); @Autowired private ApplicationContext ctx; private static App app; @Override public void afterPropertiesSet() throws Exception { app = ctx.getBean(App.class); logger.debug("{} == {} from {}", this, app, ctx); } public static <T> T getBean(Class<T> beanType) { return app.ctx.getBean(beanType); } public static Object getBean(String name) { return app.ctx.getBean(name); } } |
其实核心是
1 2 |
@Autowired ApplicationContext ctx; |