装配Bean基于XML (Bean种类、作用域、生命周期、属性依赖注入)

前端之家收集整理的这篇文章主要介绍了装配Bean基于XML (Bean种类、作用域、生命周期、属性依赖注入)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

Bean种类

1.普通bean:之前操作的都是普通bean。 ,spring直接创建A实例,并返回。

2.factorybean:是一个特殊的bean,具有工厂生成对象能力,只能生成特定的对象。
bean必须使用 factorybean接口,此接口提供方法 getObject() 用于获得特定bean。
先创建FB实例,使用调用getObject()方法,并返回方法的返回值
FB fb = new FB();
return fb.getObject();

beanfactoryfactorybean 对比?
beanfactory:工厂,用于生成任意bean。
factorybean:特殊bean,用于生成另一个特定的bean。例如:Proxyfactorybean ,此工厂bean用于生产代理。 获得代理对象实例。AOP使用

作用域

作用域:用于确定spring创建bean实例个数

取值:
singleton 单例,默认值。
prototype 多例,每执行一次getBean将获得一个实例。例如:struts整合spring,配置action多例。

配置信息:

  1. <bean id="student" class="com.fly.Student" scope="prototype" ></bean>

生命周期:
初始化和销毁
1目标方法执行前后执行后,将进行初始化或销毁。

  1. <bean id="" class="" init-method="初始化方法名称" destroy-method="销毁的方法名称">

弄个简单案例:

  1. package com.fly.spring.cycle;
  2.  
  3. /** * 猪 * @author Administrator * */
  4. public class Pig {
  5.  
  6. public void gongdi(){
  7. System.out.println("猪在拱地");
  8. }
  9.  
  10. public void init(){
  11. System.out.println("********初始化*****888");
  12. }
  13.  
  14. public void destory(){
  15. System.out.println("********销毁*****888");
  16. }
  17. }

配置:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <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">
  3.  
  4. <bean id="pig" class="com.fly.spring.cycle.Pig" init-method="init" destroy-method="destory"></bean>
  5. </beans>

测试:

  1. package com.fly.spring.cycle;
  2.  
  3. import org.junit.Test;
  4. import org.springframework.context.support.ClassPathXmlApplicationContext;
  5.  
  6. /** * 测试生命周期 * @author Administrator */
  7. public class TestCycle {
  8.  
  9. @Test
  10. public void demo(){
  11. String xmlPath = "com/fly/spring/cycle/applicationContext.xml";
  12. ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(xmlPath);
  13. Pig bean = (Pig) context.getBean("pig");
  14. bean.gongdi();
  15. //要求:1.容器必须close,销毁方法执行; 2.必须是单例的
  16. // applicationContext.getClass().getMethod("close").invoke(applicationContext);
  17. // * 此方法接口中没有定义,实现类提供
  18. context.close();
  19. }
  20. }

结果:

  1. ********初始化*****888
  2. 猪在拱地
  3. 三月 01,2017 3:16:17 下午 org.springframework.context.support.AbstractApplicationContext doClose
  4. 信息: Closing org.springframework.context.support.ClassPathXmlApplicationContext@123a439b: startup date [Wed Mar 01 15:16:17 CST 2017]; root of context hierarchy
  5. 三月 01,2017 3:16:17 下午 org.springframework.beans.factory.support.DefaultSingletonBeanRegistry destroySingletons
  6. 信息: Destroying singletons in org.springframework.beans.factory.support.DefaultListablebeanfactory@6d00a15d: defining beans [pig]; root of factory hierarchy
  7. ********销毁*****888

BeanPostProcessor 后处理Bean 这个要重点掌握

spring 提供一种机制,只要实现此接口BeanPostProcessor,并将实现类提供给spring容器,spring容器将自动执行,在初始化方法前执行before(),在初始化方法后执行after() 。 配置

Factory hook(勾子) that allows for custom modification of new bean instances,e.g. checking for marker interfaces or wrapping them with proxies

spring提供工厂勾子,用于修改实例对象,可以生成代理对象,是AOP底层

模拟
A a =new A();
a = B.before(a) –> 将a的实例对象传递给后处理bean,可以生成代理对象并返回。
a.init();
a = B.after(a);

a.addUser(); //生成代理对象,目的在目标方法后执行(例如:开启事务、提交事务)

a.destroy();

文字很枯燥,我们还是距离来证明吧。

  1. package com.fly.spring.cycle;
  2.  
  3. /** * 猪 * @author Administrator * */
  4. public class Pig {
  5.  
  6. public void gongdi(){
  7. System.out.println("猪在拱地");
  8. }
  9.  
  10. public void init(){
  11. System.out.println("********初始化*****888");
  12. }
  13.  
  14. public void destory(){
  15. System.out.println("********销毁*****888");
  16. }
  17. }

实现的类:

  1. package com.fly.spring.cycle;
  2.  
  3. import java.lang.reflect.InvocationHandler;
  4. import java.lang.reflect.Method;
  5. import java.lang.reflect.Proxy;
  6. import org.springframework.beans.BeansException;
  7. import org.springframework.beans.factory.config.BeanPostProcessor;
  8.  
  9.  
  10. public class TestBeanPostProcessor implements BeanPostProcessor {
  11.  
  12. /** * 在初始化之后执行方法 */
  13. @Override
  14. public Object postProcessAfterInitialization(Object bean,String beanName)
  15. throws BeansException {
  16. System.out.println("后方法 : " + beanName);
  17. // bean 目标对象
  18. // 生成 jdk 代理
  19. return Proxy.newProxyInstance(
  20. TestBeanPostProcessor.class.getClassLoader(),bean.getClass().getInterfaces(),new InvocationHandler(){
  21. @Override
  22. public Object invoke(Object proxy,Method method,Object[] args) throws Throwable {
  23. System.out.println("------开启事务");
  24. //执行目标方法
  25. Object obj = method.invoke(bean,args);
  26. System.out.println("------提交事务");
  27. return obj;
  28. }});
  29. }
  30.  
  31. /** * 在初始化之前执行的方法 */
  32. @Override
  33. public Object postProcessBeforeInitialization(Object bean,String beanName)
  34. throws BeansException {
  35. System.out.println("前方法 : " + beanName);
  36. return bean;
  37. }
  38.  
  39. }

测试:

  1. package com.fly.spring.cycle;
  2.  
  3. import java.lang.reflect.InvocationTargetException;
  4.  
  5. import org.junit.Test;
  6. import org.springframework.context.support.ClassPathXmlApplicationContext;
  7.  
  8. /** * 测试生命周期 * @author Administrator */
  9. public class TestCycle {
  10.  
  11. @Test
  12. public void demo(){
  13. String xmlPath = "com/fly/spring/cycle/applicationContext.xml";
  14. ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(xmlPath);
  15. Pig bean = (Pig) context.getBean("pig");
  16. bean.gongdi();
  17. //要求:1.容器必须close,销毁方法执行; 2.必须是单例的
  18. // try {
  19. // context.getClass().getMethod("close").invoke(context);
  20. // } catch (IllegalAccessException e) {
  21. // e.printStackTrace();
  22. // } catch (IllegalArgumentException e) {
  23. // e.printStackTrace();
  24. // } catch (InvocationTargetException e) {
  25. // e.printStackTrace();
  26. // } catch (NoSuchMethodException e) {
  27. // e.printStackTrace();
  28. // } catch (SecurityException e) {
  29. // e.printStackTrace();
  30. // }
  31. // * 此方法接口中没有定义,实现类提供
  32. context.close();
  33. }
  34. }

配置文件

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <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">
  3.  
  4. <bean id="pig" class="com.fly.spring.cycle.Pig" init-method="init" destroy-method="destory"></bean>
  5. <!-- 将后处理的实现类注册给spring -->
  6. <bean class="com.fly.spring.cycle.TestBeanPostProcessor"></bean>
  7. </beans>

问题1:后处理bean作用某一个目标类,还是所有目标类?
答案:所有
问题2:如何只作用一个?
答案:通过“参数2”beanName进行控制

属性依赖注入
1.依赖注入方式:手动装配 和 自动装配
2.手动装配:一般进行配置信息都采用手动
基于xml装配:构造方法、setter方法
基于注解装配:
3.自动装配:struts和spring 整合可以自动装配
byType:按类型装配
byName:按名称装配
constructor构造装配,
auto: 不确定装配。

构造方法注入:

  1. public class Person{
  2.  
  3. private Integer uid;
  4. private String username;
  5. private Integer age;
  6.  
  7. public Person(Integer uid,String username) {
  8. super();
  9. this.uid = uid;
  10. this.username = username;
  11. }
  12.  
  13. public Person(String username,Integer age) {
  14. super();
  15. this.username = username;
  16. this.age = age;
  17. }

spring配置

  1. <!-- 构造方法注入
  2. * <constructor-arg> 用于配置构造方法一个参数argument
  3. name :参数的名称
  4. value:设置普通数据
  5. ref:引用数据,一般是另一个bean id值
  6.  
  7. index :参数的索引号,从0开始 。如果只有索引,匹配到了多个构造方法时,默认使用第一个。
  8. type :确定参数类型
  9. 例如:使用名称name
  10. <constructor-arg name="username" value="jack"></constructor-arg>
  11. <constructor-arg name="age" value="18"></constructor-arg>
  12. 例如2:【类型type 和 索引 index
  13. <constructor-arg index="0" type="java.lang.String" value="1"></constructor-arg>
  14. <constructor-arg index="1" type="java.lang.Integer" value="2"></constructor-arg>
  15. -->
  16. <bean id="userId" class="com.fly.User" >
  17. <constructor-arg index="0" type="java.lang.String" value="1"></constructor-arg>
  18. <constructor-arg index="1" type="java.lang.Integer" value="2"></constructor-arg>
  19. </bean>

setter方法

  1. <!-- setter方法注入
  2. * 普通数据
  3. <property name="" value="值">
  4. 等效
  5. <property name="">
  6. <value>值
  7. * 引用数据
  8. <property name="" ref="另一个bean">
  9. 等效
  10. <property name="">
  11. <ref bean="另一个bean"/>
  12.  
  13. -->
  14. <bean id="personId" class="com.itheima.f_xml.b_setter.Person">
  15. <property name="pname" value="阳志"></property>
  16. <property name="age">
  17. <value>1234</value>
  18. </property>
  19.  
  20. <property name="homeAddr" ref="homeAddrId"></property>
  21. <property name="companyAddr">
  22. <ref bean="companyAddrId"/>
  23. </property>
  24. </bean>
  25.  
  26. <bean id="homeAddrId" class="com.itheima.f_xml.b_setter.Address">
  27. <property name="addr" value="海口"></property>
  28. <property name="tel" value="911"></property>
  29. </bean>
  30. <bean id="companyAddrId" class="com.itheima.f_xml.b_setter.Address">
  31. <property name="addr" value="深圳"></property>
  32. <property name="tel" value="120"></property>
  33. </bean>

集合注入

  1. <!-- 集合的注入都是给<property>添加标签 数组:<array> List:<list> Set:<set> Map:<map> ,map存放k/v 键值对,使用<entry>描述 Properties:<props> <prop key=""></prop> 【】 普通数据:<value> 引用数据:<ref> -->
  2. <bean id="collDataId" class="com.itheima.f_xml.e_coll.CollData" >
  3. <property name="arrayData">
  4. <array>
  5. <value>DS</value>
  6. <value>DZD</value>
  7. <value>露西</value>
  8. <value>莉莉</value>
  9. </array>
  10. </property>
  11.  
  12. <property name="listData">
  13. <list>
  14. <value>黑泽明</value>
  15. <value>宫崎骏</value>
  16. <value>小野丽莎</value>
  17. <value>苍井空</value>
  18. </list>
  19. </property>
  20.  
  21. <property name="setData">
  22. <set>
  23. <value>深圳</value>
  24. <value>广州</value>
  25. <value>东莞</value>
  26. </set>
  27. </property>
  28.  
  29. <property name="mapData">
  30. <map>
  31. <entry key="jack" value="茜茜公主"></entry>
  32. <entry>
  33. <key><value>rose</value></key>
  34. <value>白雪公主</value>
  35. </entry>
  36. </map>
  37. </property>
  38.  
  39. <property name="propsData">
  40. <props>
  41. <prop key="高富帅"></prop>
  42. <prop key="白富美"></prop>
  43. <prop key="男屌丝"></prop>
  44. </props>
  45. </property>
  46. </bean>

猜你在找的XML相关文章