场景:

在代码中需要动态获取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. Tomcat基于MSM+Memcached实现Session共享

    简述 上一篇文章,分别演示了session sticky 和 session cluster来实现会话保持的问题,但是它们缺点都不少,实际中用的很少,所以这篇文章我们还是通过Tomcat来演示一下实际 ...

  2. Kylin启动时错误:Failed to find metadata store by url: kylin_metadata@hbase 解决办法

    一.问题背景 安装kylin后使用命令 $ kylin.sh start 后出现Failed to find metadata store by url: kylin_metadata@hbase的错 ...

  3. 《Android源码设计模式》--策略模式

    No1: 定义:策略模式定义了一系列的算法,并将每一个算法封装起来,而且使它们还可以相互替换.策略模式让算法独立于使用它的客户而独立变化. No2: 使用场景: 1)针对同一类型问题的多种处理方式,仅 ...

  4. 创建NuGet包

    创建NuGet包 在创建一个NuGet包之前我们应该先创建一个以.nuspec为后缀的xml清单文件,这个清单文件描述了包的内容,在安装NuGet包的过程中这个清单文件扮演者很重要的角色.实际上它的作 ...

  5. vue.js 是如何做到数据响应的

    许多前端JavaScript框架(例如Angular,React和Vue)都有自己的数据相应引擎.通过了解相应性及其工作原理,您可以提高开发技能并更有效地使用JavaScript框架.在视频和下面的文 ...

  6. 1036 Boys vs Girls (25)(25 point(s))

    problem This time you are asked to tell the difference between the lowest grade of all the male stud ...

  7. thinkphp的_STORAGE_WRITE_ERROR_问题

    今天服务器突然报这个问题(上图所示),在thinkphp的官网上也发现有朋友碰到这个问题,定位到应该是Runtime目录没有写权限,然后试着给Application下的Runtime目录 chmod ...

  8. Codeforces Round #355 (Div. 2) A. Vanya and Fence 水题

    A. Vanya and Fence 题目连接: http://www.codeforces.com/contest/677/problem/A Description Vanya and his f ...

  9. Codeforces Round #351 (VK Cup 2016 Round 3, Div. 2 Edition) D. Bear and Two Paths 构造

    D. Bear and Two Paths 题目连接: http://www.codeforces.com/contest/673/problem/D Description Bearland has ...

  10. Mac OSX系统下通过ProxyChains-NG实现终端下的代理

    项目主页:https://github.com/rofl0r/proxychains-ng 官方说明: proxychains ng (new generation) - a preloader wh ...