在spring项目中,普通类注入获取Bean,实现ApplicationContextAware接口
Posted aizj
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在spring项目中,普通类注入获取Bean,实现ApplicationContextAware接口相关的知识,希望对你有一定的参考价值。
在平时spring项目中,某个不能注入Bean的项目中要获取Bean。
@Component public class SpringUtil implements ApplicationContextAware private static ApplicationContext applicationContext = null; public SpringUtil() public void setApplicationContext(ApplicationContext arg0) throws BeansException if (applicationContext == null) applicationContext = arg0; public static ApplicationContext getApplicationContext() return applicationContext; public static void setAppCtx(ApplicationContext webAppCtx) if (webAppCtx != null) applicationContext = webAppCtx; /** * 拿到ApplicationContext对象实例后就可以手动获取Bean的注入实例对象 */ public static <T> T getBean(Class<T> clazz) return getApplicationContext().getBean(clazz); public static <T> T getBean(String name, Class<T> clazz) throws ClassNotFoundException return getApplicationContext().getBean(name, clazz); public static final Object getBean(String beanName) return getApplicationContext().getBean(beanName); public static final Object getBean(String beanName, String className) throws ClassNotFoundException Class clz = Class.forName(className); return getApplicationContext().getBean(beanName, clz.getClass()); public static boolean containsBean(String name) return getApplicationContext().containsBean(name); public static boolean isSingleton(String name) throws NoSuchBeanDefinitionException return getApplicationContext().isSingleton(name); public static Class<?> getType(String name) throws NoSuchBeanDefinitionException return getApplicationContext().getType(name); public static String[] getAliases(String name) throws NoSuchBeanDefinitionException return getApplicationContext().getAliases(name);
在类中获取bean XXservice = (XXservice)SpringUtil.getBean(beanName);
以上是关于在spring项目中,普通类注入获取Bean,实现ApplicationContextAware接口的主要内容,如果未能解决你的问题,请参考以下文章
spring练习,在Eclipse搭建的Spring开发环境中,使用set注入方式,实现对象的依赖关系,通过ClassPathXmlApplicationContext实体类获取Bean对象(代码片段