SpringContextHolder直接从spring容器中获取bean
创建类 SpringContextHolder
import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.stereotype.Component; @Component public class SpringContextHelper implements ApplicationContextAware { private static ApplicationContext applicationContext; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { SpringContextHelper.applicationContext = applicationContext; } public static ApplicationContext getApplicationContext(){ return applicationContext; } public static Object getBean(String name){ return applicationContext.getBean(name); } /** * 从spring 上下文中获取bean * @param name * @param requiredClass * @return */ public staticT getBean(String name, Class requiredClass){ return applicationContext.getBean(name, requiredClass); } public static T getBean(Class requiredType){ return applicationContext.getBean(requiredType); } }
使用示例 :
MyService myService= SpringContextHolder.getBean(MyService.class);
String s=myService.hello("张三");
System.out.println(s);
MyService 是托管自spring容器中的bean 。在任意对象的方法代码中都可以使用SpringContextHolder类的静态方法获取spring容器中的bean .
Copyright © 叮叮声的奶酪 版权所有
备案号:鄂ICP备17018671号-1