一、Bean的装配

     bean的装配,即Bean对象的创建,容器根据代码要求来创建Bean对象后再传递给代码的过程,称为Bean的装配。

 二、默认装配方式

代码通过getBean()方式从容器获取指定的Bean示例,容器首先会调用Bean类的无参构造器,创建空值的示例对象。

三、工厂方法设计模式(为了解耦合)

 public class ServiceFactory {
public ISomeService getISomeService(){
return new SomeServiceImpl();
}
}
@Test
public void test01() {
ISomeService service=new ServiceFactory().getISomeService();
service.doSome();
}

静态工厂

public class ServiceFactory {
public static ISomeService getISomeService(){
return new SomeServiceImpl();
}
}
@Test
public void test01() {
ISomeService service=ServiceFactory.getISomeService();
service.doSome();
}

四、动态工厂Bean

public class ServiceFactory {
public ISomeService getSomeService(){
return new SomeServiceImpl();
}
}
 <!--注册动态工厂 -->
<bean id="factory" class="com.jmu.ba02.ServiceFactory"></bean>
@SuppressWarnings("resource")
@Test
public void test02() {
//创建容器对象
String resource = "com/jmu/ba02/applicationContext.xml";
ApplicationContext ac=new ClassPathXmlApplicationContext(resource);
ServiceFactory factory=(ServiceFactory) ac.getBean("factory");
ISomeService service = factory.getSomeService();
service.doSome();
}

但以上方法不好。修改如下(测试类看不到工厂,也看不到接口的实现类)

<!--注册service:动态工厂Bean-->
<bean id="myService" factory-bean="factory" factory-method="getSomeService"></bean>
@SuppressWarnings("resource")
@Test
public void test02() {
//创建容器对象
String resource = "com/jmu/ba02/applicationContext.xml";
ApplicationContext ac=new ClassPathXmlApplicationContext(resource);
ISomeService service = (ISomeService) ac.getBean("myService");
service.doSome();
}

五、静态工厂Bean

public class ServiceFactory {
public static ISomeService getSomeService(){
return new SomeServiceImpl();
}
}
 <!--注册动态工厂 :静态工厂Bean-->
<bean id="myService" class="com.jmu.ba03.ServiceFactory" factory-method="getSomeService"></bean>
@Test
@SuppressWarnings("resource")
public void test02() {
//创建容器对象
String resource = "com/jmu/ba03/applicationContext.xml";
ApplicationContext ac=new ClassPathXmlApplicationContext(resource);
ISomeService service = (ISomeService) ac.getBean("myService");
service.doSome();
}

六、Bean的装配

1、Singleton单例模式:

2、原型模式prototype:

3、request:对于每次HTTP请求,都会产生一个不同的Bean实例

4、Session:对于每次不同的HTTP session,都会产生一个不同的Bean实例

七、Bean后处理器

bean后处理器是一种特殊的Bean,容器中所有的Bean在初始化时,均会自动执行该类的两个方法,由于该Bean是由其他Bean自动调用执行,不是程序员手动创建,所有Bean无需id属性。

需要做的是,在Bean后处理器类方法中,只要对Bean类与Bean类中的方法进行判断,就可以实现对指定的Bean的指定方法进行功能扩展和增强。方法返回的Bean对象,即是增强过的对象。

代码中需要自定义Bean后处理下类,该类就是实现了接口BeanPostProcessor的类。该接口包含2个方法,分别在目标Bean初始化完毕之前和之后执行,它们的返回值为:功能被扩展或增强后的Bean对象。

 import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor; public class MyBeanPostProcessor implements BeanPostProcessor {
//bean:表示当前正在进行初始化的Bean对象
//beanName:表示当前正在进行初始化的Bean对象的id
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
// TODO Auto-generated method stub
System.out.println("执行before");
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
// TODO Auto-generated method stub
System.out.println("执行after");
return bean;
} }

MyBeanPostProcessor

 <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="myService" class="com.jmu.ba05.SomeServiceImpl"></bean>
<!--注册bean后处理器 -->
<bean class="com.jmu.ba05.MyBeanPostProcessor"></bean>
</beans>

applicationContext.xml

输出:

 执行doSome()方法
log4j:WARN No appenders could be found for logger (org.springframework.core.env.StandardEnvironment).
log4j:WARN Please initialize the log4j system properly.
执行before
执行after
执行doSome()方法

输出

八、Bean后处理器的应用

要求:增强service的doSome()

 public interface ISomeService {
String doSome();
String doOther();
}

ISomeService

 public class SomeServiceImpl implements ISomeService {

     @Override
public String doSome() {
// TODO Auto-generated method stub
System.out.println("执行doSome()方法");
return "abcd";
} @Override
public String doOther() {
// TODO Auto-generated method stub
System.out.println("执行doOther()方法");
return "fight";
} }

SomeServiceImpl

 import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy; import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor; public class MyBeanPostProcessor implements BeanPostProcessor {
//bean:表示当前正在进行初始化的Bean对象
//beanName:表示当前正在进行初始化的Bean对象的id
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
// TODO Auto-generated method stub
System.out.println("执行before");
return bean;
}
@Override
public Object postProcessAfterInitialization(final Object bean, String beanName) throws BeansException {
// TODO Auto-generated method stub
System.out.println("执行after");
if ("myService".equals(beanName)) {
Object obj = Proxy.newProxyInstance(bean.getClass().getClassLoader(), bean.getClass().getInterfaces(),
new InvocationHandler() { @Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object invoke = method.invoke(bean, args);
if ("doSome".equals(method.getName())) {
// TODO Auto-generated method stub
return ((String) invoke).toUpperCase();
}
return invoke;
}
});
//类加载器:bean.getClass().getClassLoader()
//final:内部类使用外部类的成员变量,外部成员变量需要为fianl
return obj;
}
return bean;
} }

MyBeanPostProcessor

     <bean id="myService" class="com.jmu.ba05.SomeServiceImpl"></bean>
<bean id="myService2" class="com.jmu.ba05.SomeServiceImpl"></bean>
<!--注册bean后处理器 -->
<bean class="com.jmu.ba05.MyBeanPostProcessor"></bean>

applicationContext.xml

 @SuppressWarnings("resource")
@Test
public void test02() {
//创建容器对象
String resource = "com/jmu/ba05/applicationContext.xml";
ApplicationContext ac=new ClassPathXmlApplicationContext(resource);
ISomeService service=(ISomeService) ac.getBean("myService");
System.out.println(service.doSome());
System.out.println(service.doOther()); System.out.println("--------------------"); ISomeService service2=(ISomeService) ac.getBean("myService2");
System.out.println(service2.doSome());
System.out.println(service2.doOther());
}

MyTest

输出:

执行doSome()方法
log4j:WARN No appenders could be found for logger (org.springframework.core.env.StandardEnvironment).
log4j:WARN Please initialize the log4j system properly.
执行before
执行after
执行before
执行after
执行doSome()方法
ABCD
执行doOther()方法
fight
--------------------
执行doSome()方法
abcd
执行doOther()方法
fight

output

九、定制Bean的生命周期始末

十、id与name属性

name可以包含各种字符,id的命名必须以字母开头。

Spring_Spring与IoC_Bean的装配的更多相关文章

  1. 读取xml数据装配到字典中之应用场景

    前段时间看到支付宝设置里面有个多语言这个功能,蛮有意思的,就想双休没事的话做个相关的demo玩玩,可是礼拜六被妹子拽出去玩了一天,来大上海有大半年了,基本没有出去玩过,妹子说我是超级宅男,也不带她出去 ...

  2. [spring]03_装配Bean

    3.1 JavaBean 3.1.1 JavaBean 是什么 JavaBean 是一种JAVA语言写成的可重用组件. 为写成JavaBean,类必须是具体的和公共的,并且具有无参数的构造器. Jav ...

  3. Autofac 组件、服务、自动装配 《第二篇》

    一.组件 创建出来的对象需要从组件中来获取,组件的创建有如下4种(延续第一篇的Demo,仅仅变动所贴出的代码)方式: 1.类型创建RegisterType AutoFac能够通过反射检查一个类型,选择 ...

  4. Spring bean依赖注入、bean的装配及相关注解

    依赖注入 Spring主要提供以下两种方法用于依赖注入 基于属性Setter方法注入 基于构造方法注入 Setter方法注入 例子: public class Communication { priv ...

  5. 【译】Spring 4 自动装配、自动检测、组件扫描示例

    前言 译文链接:http://websystique.com/spring/spring-auto-detection-autowire-component-scanning-example-with ...

  6. 隐式的bean发现与自动装配机制

    使用beans.xml文件进行bean的创建和注入通常是可行的,但在便利性上Spring提供了更简单的方法--自动装配 接下来我们假设一个场景:我有若干播放器(MediaPlayer{CD播放器/MP ...

  7. 解决自定义Shiro.Realm扩展类不能用注解(@Resource或@Autowire)自动装配的问题

    问题产生原因:加载Realm时其他Spring配置文件(xml)尚未加载,导致注入失败. 解决方法:编写一个设置类把注入工作提前完成. package com.xkt.shiro import org ...

  8. Spring学习记录(十一)---使用注解和自动装配

    Spring支持用注解配置Bean,更简便. 上面的组件,是根据实际情况配的.比如写的一个类,是做业务处理的,那就用注解@Service表示服务层组件,以此类推.将整体分成不同部分. 要在xml加入c ...

  9. Spring学习记录(三)---bean自动装配autowire

    Spring IoC容器可以自动装配(autowire)相互协作bean之间的关联关系,少写几个ref autowire: no ---默认情况,不自动装配,通过ref手动引用 byName---根据 ...

随机推荐

  1. 邻里街坊 golang入坑系列

    如果要追新或者怀旧,就点击https://andy-zhangtao.gitbooks.io/golang/content/ . 博客园里面的文章基本和gitbook上面是保持同步的. 这几天看了几集 ...

  2. webpack 1.x 学习总结

    webpack介绍(from github): A bundler for javascript and friends. Packs many modules into a few bundled ...

  3. 使用 Bundle 在 Activity 之间交换数据

    [toc] 使用 Bundle 在 Activity 之间交换数据 场景 当一个 Activity 启动另一个 Activity 时,常常会有一些数据需要传过去.因为两个 Activity 之间本来就 ...

  4. Go基础之--位操作中你所不知道的用法

    之前一直忽略的就是所有语言中关于位操作,觉得用处并不多,可能用到也非常简单的用法,但是其实一直忽略的是它们的用处还是非常大的,下面先回顾一下位操作符的基础 位操作符 与操作:&1 & ...

  5. J2SE-包装类

    目录 1 为什么提供包装类? 2 装箱和拆箱 3 包装类的4个特点 4 包装类类型 正文 1 为什么提供包装类? 1) 由于Java的基本数据类型功能简单,不具备面向对象的特性,实际使用时存在很多的不 ...

  6. ##1.Centos7环境准备-- openstack pike

    ##1.Centos7环境准备 openstack pike 安装 目录汇总 http://www.cnblogs.com/elvi/p/7613861.html ##.Centos7环境准备 #Ce ...

  7. 利用阿里云Centos7建站过程

    以下可能不尽详述,如有问题欢迎指出 准备过程:1. 阿里云主机一台2.域名一个 3.github个人帐号开始: 1.以root帐号登录云主机 2.安装apache [root@192 ~]# yum ...

  8. mysql如何查看索引使用情况以及优化 - guols0612

    mysql中支持hash和btree索引.innodb和myisam只支持btree索引,而memory和heap存储引擎可以支持hash和btree索引 我们可以通过下面语句查询当前索引使用情况: ...

  9. 原生Js实现拖拽(适用于pc和移动端)

    效果: HTML和CSS部分 <!DOCTYPE html> <html lang="en"> <head> <meta charset= ...

  10. ABP module-zero +AdminLTE+Bootstrap Table+jQuery权限管理系统第十七节--Quartz与ABP框架Abp.Quartz及扩展

    ABP+AdminLTE+Bootstrap Table权限管理系统一期 Github:https://github.com/Jimmey-Jiang/ABP-ASP.NET-Boilerplate- ...