场景:

在代码中需要动态获取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配置文件中声明,要么加上注解

@SpringContext通过实现ApplicationContextAware接口动态获取bean的更多相关文章

  1. Spring中使用两种Aware接口自定义获取bean

    在使用spring编程时,常常会遇到想根据bean的名称来获取相应的bean对象,这时候,就可以通过实现BeanFactoryAware来满足需求,代码很简单: @Servicepublic clas ...

  2. web 工程中利用Spring的 ApplicationContextAware接口自动注入bean

    最常用的办法就是用 ClassPathXmlApplicationContext, FileSystemClassPathXmlApplicationContext, FileSystemXmlApp ...

  3. 如何手动获取Spring容器中的bean(ApplicationContextAware 接口)

    ApplicationContextAware 接口的作用 先来看下Spring API 中对于 ApplicationContextAware 这个接口的描述:   即是说,当一个类实现了这个接口之 ...

  4. SpringBoot27 JDK动态代理详解、获取指定的类类型、动态注册Bean、接口调用框架

    1 JDK动态代理详解 静态代理.JDK动态代理.Cglib动态代理的简单实现方式和区别请参见我的另外一篇博文. 1.1 JDK代理的基本步骤 >通过实现InvocationHandler接口来 ...

  5. Spring - 运行时获取bean(ApplicationContextAware接口)

    默认情况下,我们的bean都是单例模式(即从容器初始化到销毁只保持一个实例).当一个bean需要引用另外一个bean,我们往往会通过bean属性的方式通过依赖注入来引用另外一个bean.那么问题就来了 ...

  6. 【ApplicationContext】通过实现ApplicationContextAware接口获取bean

    SpringApplicationUtils.java import org.springframework.beans.BeansException; import org.springframew ...

  7. 使用Spring容器动态注册和获取Bean

    有时候需要在运行时动态注册Bean到Spring容器,并根据名称获取注册的Bean.比如我们自己的SAAS架构的系统需要调用ThingsBoard API和Thingsboard交互,就可以通过Thi ...

  8. 从Spring容器中获取Bean。ApplicationContextAware

    引言:我们从几个方面有逻辑的讲述如何从Spring容器中获取Bean.(新手勿喷) 1.我们的目的是什么? 2.方法是什么(可变的细节)? 3.方法的原理是什么(不变的本质)? 1.我们的目的是什么? ...

  9. ApplicationContextAware 快速获取bean

    在Web应用中,Spring容器通常采用声明式方式配置产生:开发者只要在web.xml中配置一个Listener,该Listener将会负责初始化Spring容器,MVC框架可以直接调用Spring容 ...

随机推荐

  1. 使用VisualStudio2015开发QT项目

    一直习惯用VS,做QT项目时,不停的来回切IDE有些不方便.研究了一下QT的编译. 实际QT编译的机制和cmake是相同的,QT的IDE使用pro文件进行项目管理.QMake通过解析pro工程文件,生 ...

  2. HDU - 1716 排列2 水题

    排列2 Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others) Total Submis ...

  3. ACM 水果 hdu 1263 一题多解

    题目:http://acm.hdu.edu.cn/showproblem.php?pid=1263 文章末有相应的一些测试数据供参考. 传统的数组解题方式 思路一: 三种属性的数据放在一个结构体里面, ...

  4. [leetcode tree]107. Binary Tree Level Order Traversal II

    Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left ...

  5. [leetcode shell]194. Transpose File

    Given a text file file.txt, transpose its content. You may assume that each row has the same number ...

  6. python orm字段解析

    null # 是否可以为空 default # 默认值 primary_key # 主键 db_column # 列名 db_index # 索引(db_index=True) unique # 唯一 ...

  7. 快速排序之C++实现

    快速排序之C++实现 一趟快速排序的算法是: 1)设置两个变量i.j,排序开始的时候:i=0,j=N-1: 2)以第一个数组元素作为关键数据,赋值给key,即key=A[0]: 3)从j开始向前搜索, ...

  8. [BZOJ3507][CQOI2014]通配符匹配(DP+Hash)

    显然f[i][j]表示S匹配到第i个通配符,T匹配到第j个字符,是否可行. 一次一起转移两个通配符之间的所有字符,Hash判断. 稍微有点细节.常数极大卡时过排名倒数,可能是没自然溢出的原因. #in ...

  9. 鸟哥的私房菜:Linux磁盘与文件系统原理

    1 硬盘物理组成     //原理 磁头负责读写     磁道(硬盘同半径的一圈) 磁柱(所有盘磁道叠加起来的柱)     扇区(2条半径将磁道分开的一个扇形区域,是磁盘的最小存储单位) ------ ...

  10. bzoj 1176: [Balkan2007]Mokia&&2683: 简单题 -- cdq分治

    2683: 简单题 Time Limit: 50 Sec  Memory Limit: 128 MB Description 你有一个N*N的棋盘,每个格子内有一个整数,初始时的时候全部为0,现在需要 ...