spring:如何用代码动态向容器中添加或移除Bean ?
先来看一张类图:

有一个业务接口IFoo,提供了二个实现类:FooA及FooB,默认情况下,FooA使用@Component由Spring自动装配,如果出于某种原因,在运行时需要将IFoo的实现,则FooA换成FooB,可以用代码动态先将FooA的实例从容器中删除,然后再向容器中注入FooB的实例,代码如下:
1、IFoo接口:
package yjmyzz;
import org.springframework.beans.factory.DisposableBean;
public interface IFoo extends DisposableBean {
public void foo();
}
2、 FooA实现
package yjmyzz; import org.springframework.stereotype.Component; //注:这里的名称fooA,仅仅只是为了后面演示时看得更清楚,非必需
@Component("fooA")
public class FooA implements IFoo { public FooA() {
System.out.println("FooA is created!");
} public void foo() {
System.out.println("FooA.foo()");
} public void destroy() throws Exception {
System.out.println("FooA.destroy()"); }
}
3、FooB实现
package yjmyzz;
public class FooB implements IFoo {
public FooB() {
System.out.println("FooB is created!");
}
public void foo() {
System.out.println("FooB.foo()");
}
public void destroy() throws Exception {
System.out.println("FooB.destroy()");
}
}
4、测试程序AppDemo
package yjmyzz; import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.support.AbstractRefreshableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; /**
* 演示在运行时,动态向容器中添加、移除Bean
* author:菩提树下的杨过 http://yjmyzz.cnblogs.cm/
*/
public class AppDemo { public static void main(String[] args) { ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml"); //从context中取出FooA实例
IFoo f = ctx.getBean(IFoo.class);
f.foo();//FooA.foo() //输出IFoo的Bean基本信息
System.out.println(f.getClass());//class yjmyzz.FooA
String beanName = ctx.getBeanNamesForType(IFoo.class)[0];
System.out.println(beanName);//fooA
System.out.println(ctx.isSingleton(beanName));//true //销毁FooA实例
removeBean(ctx, beanName);
System.out.println(ctx.containsBean(beanName));//false
System.out.println("------------"); //注入新Bean
beanName = "fooB";
addBean(ctx, beanName, FooB.class); //取出新实例
f = ctx.getBean(beanName, IFoo.class);
f.foo(); //输出IFoo的Bean基本信息
System.out.println(f.getClass());
beanName = ctx.getBeanNamesForType(IFoo.class)[0];
System.out.println(beanName);//fooB
System.out.println(ctx.isSingleton(beanName));//true System.out.println("------------");
showAllBeans(ctx); ctx.close(); } /**
* 向容器中动态添加Bean
*
* @param ctx
* @param beanName
* @param beanClass
*/
static void addBean(AbstractRefreshableApplicationContext ctx, String beanName, Class beanClass) {
BeanDefinitionRegistry beanDefReg = (DefaultListableBeanFactory) ctx.getBeanFactory();
BeanDefinitionBuilder beanDefBuilder = BeanDefinitionBuilder.genericBeanDefinition(beanClass);
BeanDefinition beanDef = beanDefBuilder.getBeanDefinition();
if (!beanDefReg.containsBeanDefinition(beanName)) {
beanDefReg.registerBeanDefinition(beanName, beanDef);
}
} /**
* 从容器中移除Bean
*
* @param ctx
* @param beanName
*/
static void removeBean(AbstractRefreshableApplicationContext ctx, String beanName) {
BeanDefinitionRegistry beanDefReg = (DefaultListableBeanFactory) ctx.getBeanFactory();
beanDefReg.getBeanDefinition(beanName);
beanDefReg.removeBeanDefinition(beanName);
} /**
* 遍历输出所有Bean的信息
*/
static void showAllBeans(AbstractRefreshableApplicationContext ctx) {
//遍历
for (String name : ctx.getBeanDefinitionNames()) {
System.out.println("name:" + name + ",class:" + ctx.getBean(name).getClass());
}
}
}
beans.xml配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <context:component-scan base-package="yjmyzz" /> </beans>
输出:
FooA is created!
FooA.foo()
class yjmyzz.FooA
fooA
true
FooA.destroy()
false
------------
FooB is created!
FooB.foo()
class yjmyzz.FooB
fooB
true
------------
name:org.springframework.context.annotation.internalConfigurationAnnotationProcessor,class:class org.springframework.context.annotation.ConfigurationClassPostProcessor
name:org.springframework.context.annotation.internalAutowiredAnnotationProcessor,class:class org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor
name:org.springframework.context.annotation.internalRequiredAnnotationProcessor,class:class org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor
name:org.springframework.context.annotation.internalCommonAnnotationProcessor,class:class org.springframework.context.annotation.CommonAnnotationBeanPostProcessor
name:org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor,class:class org.springframework.context.annotation.ConfigurationClassPostProcessor$ImportAwareBeanPostProcessor
name:org.springframework.context.annotation.ConfigurationClassPostProcessor.enhancedConfigurationProcessor,class:class org.springframework.context.annotation.ConfigurationClassPostProcessor$EnhancedConfigurationBeanPostProcessor
name:fooB,class:class yjmyzz.FooB
FooB.destroy()
spring:如何用代码动态向容器中添加或移除Bean ?的更多相关文章
- 六、spring之通过FactoryBean为ioc容器中添加组件
前面我们已经介绍了几种为容器中添加组件的方法,今天一起学习通过FactoryBean添加组件的方法. 首先我们准备一个类,也就是我们需要注册进spring的ioc容器中的类 类Color: // 不必 ...
- js如何实现动态在表格中添加标题和去掉标题?
js如何实现动态在表格中添加标题和去掉标题? 一.总结 1.通过table标签的createCaption(),deleteCaption()方法实现. document.getElementById ...
- sencha动态向容器里添加控件出现重叠问题
sencha动态向容器里添加控件出现重叠问题原因是由于动态生成控件的id有重复导致的.(js取时间到毫秒来做id,放在for里面会出现几个控件id是相同的情况.).解决掉重复id的问题就好了. 版权声 ...
- ajax异步获取数据后动态向表格中添加数据(行)
因为某些原因,项目中突然需要做自己做个ajax异步获取数据后动态向表格中添加数据的页面,网上找了半天都没有 看到现成的,决定自己写个例子 1.HTML页面 <!doctype html> ...
- spring源码 — 二、从容器中获取Bean
getBean 上一节中说明了容器的初始化,也就是把Bean的定义GenericBeanDefinition放到了容器中,但是并没有初始化这些Bean.那么Bean什么时候会初始化呢? 在程序第一个主 ...
- Spring注解驱动开发04(给容器中注册组件的方式)
给容器中注册组件的方式 1. 组件注解标注 + 包扫描(适用于自己写的类) //控制层组件 @Controller public class PersonController { } //业务逻辑层组 ...
- vector容器中添加和删除元素
添加元素: 方法一: insert() 插入元素到Vector中 iterator insert( iterator loc, const TYPE &val ); //在指定位置loc前插入 ...
- jQuery中添加/改变/移除改变CSS样式例子
在jquery中对于div样式操作我们会使用到CSS() removeClass() addClass()方法来操作了,下面我们就整理了几个例子大家一起来看看吧. CSS()方法改变CSS样式 ...
- 2.spring源码-BeanPostProcessor后置处理之ApplicationContextAwareProcessor,实现spring容器中某一个类的bean对象在初始化时需要得到Spring容器内容。
需求:我们的需求是,在spring初始化完毕时,使我们自定义一个类Bird类可以得到spring容器内容. 实现步骤: 1.首先我们来看一下ApplicationContextAwareProcess ...
随机推荐
- vs2015密钥 企业版 专业版 (vs.net)
专业版:HMGNV-WCYXV-X7G9W-YCX63-B98R2企业版:HM6NR-QXX7C-DFW2Y-8B82K-WTYJV
- Symantec Backup Exec备份作业服务器盘符变更
Symantec Backup Exec的备份作业中,如果某个服务器的磁盘更改了盘符,如果不修改备份作业里面的相关配置,就会出现类似下面的错误信息,如下截图所示 因为这台服务器上我们将原先的G盘的盘符 ...
- 从Prototype学习JavaScript面向对象编程
概述 JavaScript是一种基于对象的编程语言.它是灵活的,既有面向过程(也就是面向函数)的编程,也有面向对象的编程.因此我称它是基于对象的编程语言. 对于JavaScript的面向过程的编程特性 ...
- coursera机器学习-logistic回归,正则化
#对coursera上Andrew Ng老师开的机器学习课程的笔记和心得: #注:此笔记是我自己认为本节课里比较重要.难理解或容易忘记的内容并做了些补充,并非是课堂详细笔记和要点: #标记为<补 ...
- mysql-3 检索数据(1)
SELECT 语句 SELECT检索表数据,必须至少给出两条信息--------想选择什么,以及从什么地方选择. 检索一个列 SELECT prod_name FROM products; 上述语句利 ...
- linux线程同步(4)-自旋锁
自旋锁与互斥量功能一样,唯一一点不同的就是互斥量阻塞后休眠让出cpu,而自旋锁阻塞后不会让出cpu,会一直忙等待,直到得到锁!!! 自旋锁在用户态使用的比较少,在内核使用的比较多!自旋锁的使用场景:锁 ...
- 零拷贝传输(zero-copy transfer)——sendfile()
做Web服务器时通常需要将文件传送出去,其中一种方法是通过定义一个buffer每次读取文件发送给接收端.大多数服务器会选择sendfile的方式,nginx实现时就是采用这种方式.对于并发搞得服务器性 ...
- Ganglia安装扩容
现有的环境中Hbase集群的机器需要安装ganglia,遂采取了以下步骤. 查看机器的信息, uname –a cat /etc/issue 查看当前环境是x86的,安装的是red hat 6.4 之 ...
- C# WebService动态调用
前言 站在开发者的角度,WebService 技术确实是不再“时髦”.甚至很多人会说,我们不再用它.当然,为了使软件可以更简洁,更有层次,更易于实现缓存等机制,我是非常建议将 SOAP 转为 REST ...
- LinuxAsm#Chapter10
Dividing and Conquering Book: Assembly Language step by step Complexity kills programs. Remember to ...