spring管理的类如何调用非spring管理的类
生活随笔
收集整理的這篇文章主要介紹了
spring管理的类如何调用非spring管理的类
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
spring管理的類如何調(diào)用非spring管理的類.
就是使用一個spring提供的感知概念,在容器啟動的時候,注入上下文即可.
下面是一個工具類.
?
1 import org.springframework.beans.BeansException; 2 import org.springframework.context.ApplicationContext; 3 import org.springframework.context.ApplicationContextAware; 4 import org.springframework.stereotype.Component; 5 6 /** 7 * spring上下文的持有者: 8 * ApplicationContextAware 可感知ApplicationContex, 9 * 只要實現(xiàn)了該接口的類,交給Spring管理后,Spring就能感知到, 10 * 感知后就會調(diào)用setApplicationContext注入當(dāng)前容器的上下文. 11 * @author lne 12 */ 13 @Component 14 public class SpringApplicationContextHolder implements ApplicationContextAware { 15 16 // 使用一個變量接受ApplicationContext 17 private static ApplicationContext ctx = null; 18 19 @Override 20 public void setApplicationContext(ApplicationContext ctx) throws BeansException { 21 System.out.println(ctx); 22 SpringApplicationContextHolder.ctx = ctx; 23 } 24 25 public static Object getBean(String name) { 26 27 return ctx.getBean(name); 28 } 29 30 public static Object getBean(Class clazz) { 31 32 return ctx.getBean(clazz); 33 } 34 }?
轉(zhuǎn)載于:https://www.cnblogs.com/applerosa/p/6016852.html
總結(jié)
以上是生活随笔為你收集整理的spring管理的类如何调用非spring管理的类的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java内部类的定义和使用
- 下一篇: 软考考前冲刺第十三章UML建模