转载自:http://penghuaiyi.iteye.com/blog/2042296
场景:
在代码中需要动态获取spring管理的bean
代码:
SpringContextUtils.java
package com.winner.utils; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.stereotype.Component; /** * Spring的工具类,用来获得配置文件中的bean */ @Component public class SpringContextUtils implements ApplicationContextAware { private static ApplicationContext applicationContext; /** * 当继承了ApplicationContextAware类之后,那么程序在调用 getBean(String)的时候会自动调用该方法, * 不用自己操作 */ @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { SpringContextUtils.applicationContext = applicationContext; } /*** * 根据一个bean的id获取配置文件中相应的bean */ public static Object getBean(String beanId) throws BeansException { if (applicationContext.containsBean(beanId)) { applicationContext.getBean(beanId); } return null; } /*** * 根据一个bean的类型获取配置文件中相应的bean */ public static <T> T getBeanByClass(Class<T> requiredType) throws BeansException { return applicationContext.getBean(requiredType); } /** * 如果BeanFactory包含一个与所给名称匹配的bean定义,则返回true */ public static boolean containsBean(String name) { return applicationContext.containsBean(name); } public static ApplicationContext getApplicationContext() { return SpringContextUtils.applicationContext; } }
这几个注解所在的包是
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.2.5.RELEASE</version> </dependency>
SpringContextUtils必须放在Spring容器中
要么在xml配置文件中声明,要么加上注解
时间: 2024-11-04 07:15:25