先来看一张类图:

有一个业务接口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 ?的更多相关文章

  1. 六、spring之通过FactoryBean为ioc容器中添加组件

    前面我们已经介绍了几种为容器中添加组件的方法,今天一起学习通过FactoryBean添加组件的方法. 首先我们准备一个类,也就是我们需要注册进spring的ioc容器中的类 类Color: // 不必 ...

  2. js如何实现动态在表格中添加标题和去掉标题?

    js如何实现动态在表格中添加标题和去掉标题? 一.总结 1.通过table标签的createCaption(),deleteCaption()方法实现. document.getElementById ...

  3. sencha动态向容器里添加控件出现重叠问题

    sencha动态向容器里添加控件出现重叠问题原因是由于动态生成控件的id有重复导致的.(js取时间到毫秒来做id,放在for里面会出现几个控件id是相同的情况.).解决掉重复id的问题就好了. 版权声 ...

  4. ajax异步获取数据后动态向表格中添加数据(行)

    因为某些原因,项目中突然需要做自己做个ajax异步获取数据后动态向表格中添加数据的页面,网上找了半天都没有 看到现成的,决定自己写个例子 1.HTML页面 <!doctype html> ...

  5. spring源码 — 二、从容器中获取Bean

    getBean 上一节中说明了容器的初始化,也就是把Bean的定义GenericBeanDefinition放到了容器中,但是并没有初始化这些Bean.那么Bean什么时候会初始化呢? 在程序第一个主 ...

  6. Spring注解驱动开发04(给容器中注册组件的方式)

    给容器中注册组件的方式 1. 组件注解标注 + 包扫描(适用于自己写的类) //控制层组件 @Controller public class PersonController { } //业务逻辑层组 ...

  7. vector容器中添加和删除元素

    添加元素: 方法一: insert() 插入元素到Vector中 iterator insert( iterator loc, const TYPE &val ); //在指定位置loc前插入 ...

  8. jQuery中添加/改变/移除改变CSS样式例子

    在jquery中对于div样式操作我们会使用到CSS() removeClass() addClass()方法来操作了,下面我们就整理了几个例子大家一起来看看吧.     CSS()方法改变CSS样式 ...

  9. 2.spring源码-BeanPostProcessor后置处理之ApplicationContextAwareProcessor,实现spring容器中某一个类的bean对象在初始化时需要得到Spring容器内容。

    需求:我们的需求是,在spring初始化完毕时,使我们自定义一个类Bird类可以得到spring容器内容. 实现步骤: 1.首先我们来看一下ApplicationContextAwareProcess ...

随机推荐

  1. 1.2 基础知识——关于猪皮(GP,Generic Practice)

    摘要: 这是<CMMI快乐之旅>系列文章之一.说起猪皮(GP,Generic Practice),真的让人又爱又恨,中文翻译叫通用实践.CMMI标准中每个级别包含几个PA,每个PA又包含几 ...

  2. javascript-建造者模式

    建造者模式笔记 1.工厂模式主要是为了创建对象实例或者类簇(抽象工厂),关心的是最终产出(创建)的是什么,不关心你创建的整个过程,仅仅需要知道你最终创建的结果 2.建造者模式目的也是为了创建对象,但是 ...

  3. sql server 基础教程[温故而知新三]

    子曰:“温故而知新,可以为师矣.”孔子说:“温习旧知识从而得知新的理解与体会,凭借这一点就可以成为老师了.“ 尤其是咱们搞程序的人,不管是不是全栈工程师,都是集十八般武艺于一身.不过有时候有些知识如果 ...

  4. 烂泥:yum的使用及配置

    本文由秀依林枫提供友情赞助,首发于烂泥行天下. 最近由于服务器需求,需要在公司内网搭建内网yum源. 搭建内网yum源需要分以下几个步骤,如下: 1. yum是什么 2. repo文件是什么 3. r ...

  5. ubuntu同时安装qt4.8和qt5.7

    这是ubuntu默认安装(从apt安装)的路径和相关文件,建议编译安装到/opt目录下,使用./configure --prefix=/opt/Qt4.8 /usr/share/qt4 /usr/sh ...

  6. spark mllib配置pom.xml错误 Multiple markers at this line Could not transfer artifact net.sf.opencsv:opencsv:jar:2.3 from/to central (https://repo.maven.apache.org/maven2): repo.maven.apache.org

    刚刚spark mllib,在maven repository网站http://mvnrepository.com/中查询mllib后得到相关库的最新dependence为: <dependen ...

  7. linux 文件管理以及其相关指令

    Linux简介 严格的来讲,Linux 不算是一个操作系统,只是一个 Linux 系统中的内核, 即计算机软件与硬件通讯之间的平台:Linux的全称是GNU/Linux,这才算是一个真正意义上的Lin ...

  8. 新手ui设计师必备——切图规范

    图文并茂,浅显易懂. 使用markman标注. 资源链接: 图片来自http://www.ui.cn/detail/56347.html 本文作者starof,因知识本身在变化,作者也在不断学习成长, ...

  9. MMORPG大型游戏设计与开发(客户端架构 part4 of vegine)

    昨天是七夕,祝大家都过的快乐,希望这句迟到的问候不会造成大家心中的困扰.这一节讲到了前端比较重要的模块,性能以及调试异常模块.一个应用的性能往往是最核心的部分,就像人身体的各个器官一样,一小部分也不能 ...

  10. Unity C# 反编译

    前言 结合前篇:[反编译U3D]Decompile Unity Resources 修正 本篇说说如何查看unity项目(apk) 的源代码,前提是这个apk的代码未经过加密. 写这篇的目地就是看看别 ...