场景:
在代码中需要动态获取spring管理的bean
目前遇到的主要有两种场景:
1.在工具类中需要调用某一个Service完成某一个功能,如DictUtils
2.在实现了Runnable接口的任务类中需要调用某一个Service完成run方法中的功能!
代码:
SpringContextUtils.java
import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.stereotype.Component; @Component public class ApplicationContextUtils implements ApplicationContextAware { private static ApplicationContext applicationContext; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { ApplicationContextUtils.applicationContext = applicationContext; System.out.println("spring容器在项目构建的时候就执行了"); String[] beanDefinitionNames = applicationContext.getBeanDefinitionNames(); for (String beanDefinitionName : beanDefinitionNames) { //beanDefinitionName是容器中bean实例的id //<bean id="">对应此处的id System.out.println(beanDefinitionName); } } /** * 当通过接口多个实现时,需要用 beanName区分 * * @param name 注册的 bean名称 * @param clazz 注册的 bean类型 * @param <T> * @return */ public static <T> T getBean(String name, Class<T> clazz) { if (applicationContext == null){ return null; } return applicationContext.getBean(name, clazz); } /*** * 根据一个bean的类型获取配置文件中相应的bean */ public static <T> T getBeanByClass(Class<T> requiredType) { if (applicationContext == null) { return null; } return applicationContext.getBean(requiredType); } public static ApplicationContext getApplicationContext() { return ApplicationContextUtils.applicationContext; } }
控制台输出
spring容器在项目构建的时候就执行了 sqlSessionFactory org.mybatis.spring.mapper.MapperScannerConfigurer#0 dataSource org.springframework.beans.factory.config.PropertyPlaceholderConfigurer#0 transactionManager org.springframework.aop.config.internalAutoProxyCreator org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0 org.springframework.transaction.interceptor.TransactionInterceptor#0 org.springframework.transaction.config.internalTransactionAdvisor myTbItemServiceImpl org.springframework.context.annotation.internalConfigurationAnnotationProcessor org.springframework.context.annotation.internalAutowiredAnnotationProcessor org.springframework.context.annotation.internalRequiredAnnotationProcessor org.springframework.context.annotation.internalCommonAnnotationProcessor springContext org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor org.springframework.context.annotation.ConfigurationClassPostProcessor.enhancedConfigurationProcessor tbItemMapper
@Service("myTbItemServiceImpl") public class TbItemServiceImpl implements ITbItemService
这几个注解所在的包是
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.2.5.RELEASE</version>
</dependency>
SpringContextUtils必须放在Spring容器中
要么在xml配置文件中声明,要么加上注解