一、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. 校验ISBN的方法

     国际标准书号(International Standard Book Number,ISBN:是国际通用的图书或独立的出版物(除定期出版的期刊)代码.出版社可以通过国际标准书号清晰的辨认所有非期刊书 ...

  2. 2734:十进制到八进制-poj

    总时间限制:  1000ms 内存限制:  65536kB 描述 把一个十进制正整数转化成八进制. 输入 一行,仅含一个十进制表示的整数a(0 < a < 65536). 输出 一行,a的 ...

  3. # openVPN+LDAP AD认证,组权限管理

    # openVPN+LDAP AD认证,组权限管理 原创内容http://www.cnblogs.com/elvi/p/7661178.html # openVPN+LDAP AD认证,组权限管理 # ...

  4. CCF-201412-1-门禁系统

    问题描述 试题编号: 201412-1 试题名称: 门禁系统 时间限制: 1.0s 内存限制: 256.0MB 问题描述: 问题描述 涛涛最近要负责图书馆的管理工作,需要记录下每天读者的到访情况.每位 ...

  5. mysql分区分表

    为毛要分表和分区,,,,所有数据库的通病,文件越大,性能越低...那问题就来了.数据越多文件越大...无解?哎,所以说知道 为毛要分区了吧!那分表又是毛线?分表就是把一张表拆分成若干表,,,根据情况常 ...

  6. LNMP1.3 一键配置环境,简单方便

    系统需求: CentOS/RHEL/Fedora/Debian/Ubuntu/Raspbian Linux系统 需要3GB以上硬盘剩余空间 需要128MB以上内存(如果为128MB的小内存VPS,Xe ...

  7. hdu4416 Good Article Good sentence (后缀数组)

    题意:问a串中有多少种字符串集合B中没有的连续子串. a的长度10^5,B中的总长度为不超过10^5. 解法:后缀数组题目:后缀数组能够非常easy算出来一个串中有多少种子串. 把a和B集合连起来.求 ...

  8. HDU 4911 Inversion 树状数组求逆序数对

    显然每次交换都能降低1 所以求出逆序数对数,然后-=k就好了.. . _(:зゝ∠)_ #include<stdio.h> #include<string.h> #includ ...

  9. Android 夜间模式changeskin小结

    @author vivian8725118 @CSDN http://blog.csdn.net/vivian8725118 @简书 http://www.jianshu.com/p/832e9776 ...

  10. 怎样在Ubuntu Scope中定义设置变量并读取

    在本遍文章中,我们来解说怎么对我们的Ubuntu Scope进行设置.对Scope而言,有些时候我们希望可以使用设置来改变我们的显示.或对我们的搜索进行又一次定义.关于很多其它Scope的开发,请參阅 ...