装配Bean基于XML (Bean种类、作用域、生命周期、属性依赖注入)
2017-03-01 15:55
579 查看
Bean种类
1.普通bean:之前操作的都是普通bean。 ,spring直接创建A实例,并返回。2.FactoryBean:是一个特殊的bean,具有工厂生成对象能力,只能生成特定的对象。
bean必须使用 FactoryBean接口,此接口提供方法 getObject() 用于获得特定bean。
先创建FB实例,使用调用getObject()方法,并返回方法的返回值
FB fb = new FB();
return fb.getObject();
BeanFactory 和 FactoryBean 对比?
BeanFactory:工厂,用于生成任意bean。
FactoryBean:特殊bean,用于生成另一个特定的bean。例如:ProxyFactoryBean ,此工厂bean用于生产代理。 获得代理对象实例。AOP使用
作用域
作用域:用于确定spring创建bean实例个数取值:
singleton 单例,默认值。
prototype 多例,每执行一次getBean将获得一个实例。例如:struts整合spring,配置action多例。
配置信息:
<bean id="student" class="com.fly.Student" scope="prototype" ></bean>
生命周期:
初始化和销毁
1目标方法执行前后执行后,将进行初始化或销毁。
<bean id="" class="" init-method="初始化方法名称" destroy-method="销毁的方法名称">
弄个简单案例:
package com.fly.spring.cycle; /** * 猪 * @author Administrator * */ public class Pig { public void gongdi(){ System.out.println("猪在拱地"); } public void init(){ System.out.println("********初始化*****888"); } public void destory(){ System.out.println("********销毁*****888"); } }
配置:
<?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="pig" class="com.fly.spring.cycle.Pig" init-method="init" destroy-method="destory"></bean> </beans>
测试:
package com.fly.spring.cycle; import org.junit.Test; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * 测试生命周期 * @author Administrator */ public class TestCycle { @Test public void demo(){ String xmlPath = "com/fly/spring/cycle/applicationContext.xml"; ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(xmlPath); Pig bean = (Pig) context.getBean("pig"); bean.gongdi(); //要求:1.容器必须close,销毁方法执行; 2.必须是单例的 // applicationContext.getClass().getMethod("close").invoke(applicationContext); // * 此方法接口中没有定义,实现类提供 context.close(); } }
结果:
********初始化*****888 猪在拱地 三月 01, 2017 3:16:17 下午 org.springframework.context.support.AbstractApplicationContext doClose 信息: Closing org.springframework.context.support.ClassPathXmlApplicationContext@123a439b: startup date [Wed Mar 01 15:16:17 CST 2017]; root of context hierarchy 三月 01, 2017 3:16:17 下午 org.springframework.beans.factory.support.DefaultSingletonBeanRegistry destroySingletons 信息: Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@6d00a15d: defining beans [pig]; root of factory hierarchy ********销毁*****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();
看文字很枯燥,我们还是距离来证明吧。
package com.fly.spring.cycle; /** * 猪 * @author Administrator * */ public class Pig { public void gongdi(){ System.out.println("猪在拱地"); } public void init(){ System.out.println("********初始化*****888"); } public void destory(){ System.out.println("********销毁*****888"); } }
实现的类:
package com.fly.spring.cycle; 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 TestBeanPostProcessor implements BeanPostProcessor { /** * 在初始化之后执行的方法 */ @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { System.out.println("后方法 : " + beanName); // bean 目标对象 // 生成 jdk 代理 return Proxy.newProxyInstance( TestBeanPostProcessor.class.getClassLoader(), bean.getClass().getInterfaces(), new InvocationHandler(){ @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("------开启事务"); //执行目标方法 Object obj = method.invoke(bean, args); System.out.println("------提交事务"); return obj; }}); } /** * 在初始化之前执行的方法 */ @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { System.out.println("前方法 : " + beanName); return bean; } }
测试:
package com.fly.spring.cycle; import java.lang.reflect.InvocationTargetException; import org.junit.Test; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * 测试生命周期 * @author Administrator */ public class TestCycle { @Test public void demo(){ String xmlPath = "com/fly/spring/cycle/applicationContext.xml"; ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(xmlPath); Pig bean = (Pig) context.getBean("pig"); bean.gongdi(); //要求:1.容器必须close,销毁方法执行; 2.必须是单例的 // try { // context.getClass().getMethod("close").invoke(context); // } catch (IllegalAccessException e) { // e.printStackTrace(); // } catch (IllegalArgumentException e) { // e.printStackTrace(); // } catch (InvocationTargetException e) { // e.printStackTrace(); // } catch (NoSuchMethodException e) { // e.printStackTrace(); // } catch (SecurityException e) { // e.printStackTrace(); // } // * 此方法接口中没有定义,实现类提供 context.close(); } }
配置文件:
<?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="pig" class="com.fly.spring.cycle.Pig" init-method="init" destroy-method="destory"></bean> <!-- 将后处理的实现类注册给spring --> <bean class="com.fly.spring.cycle.TestBeanPostProcessor"></bean> </beans>
问题1:后处理bean作用某一个目标类,还是所有目标类?
答案:所有
问题2:如何只作用一个?
答案:通过“参数2”beanName进行控制
属性依赖注入
1.依赖注入方式:手动装配 和 自动装配。
2.手动装配:一般进行配置信息都采用手动
基于xml装配:构造方法、setter方法
基于注解装配:
3.自动装配:struts和spring 整合可以自动装配
byType:按类型装配
byName:按名称装配
constructor构造装配,
auto: 不确定装配。
构造方法注入:
public class Person{ private Integer uid; private String username; private Integer age; public Person(Integer uid, String username) { super(); this.uid = uid; this.username = username; } public Person(String username, Integer age) { super(); this.username = username; this.age = age; }
spring配置
<!-- 构造方法注入 * <constructor-arg> 用于配置构造方法一个参数argument name :参数的名称 value:设置普通数据 ref:引用数据,一般是另一个bean id值 index :参数的索引号,从0开始 。如果只有索引,匹配到了多个构造方法时,默认使用第一个。 type :确定参数类型 例如:使用名称name <constructor-arg name="username" value="jack"></constructor-arg> <constructor-arg name="age" value="18"></constructor-arg> 例如2:【类型type 和 索引 index】 <constructor-arg index="0" type="java.lang.String" value="1"></constructor-arg> <constructor-arg index="1" type="java.lang.Integer" value="2"></constructor-arg> --> <bean id="userId" class="com.fly.User" > <constructor-arg index="0" type="java.lang.String" value="1"></constructor-arg> <constructor-arg index="1" type="java.lang.Integer" value="2"></constructor-arg> </bean>
setter方法
<!-- setter方法注入 * 普通数据 <property name="" value="值"> 等效 <property name=""> <value>值 * 引用数据 <property name="" ref="另一个bean"> 等效 <property name=""> <ref bean="另一个bean"/> --> <bean id="personId" class="com.itheima.f_xml.b_setter.Person"> <property name="pname" value="阳志"></property> <property name="age"> <value>1234</value> </property> <property name="homeAddr" ref="homeAddrId"></property> <property name="companyAddr"> <ref bean="companyAddrId"/> </property> </bean> <bean id="homeAddrId" class="com.itheima.f_xml.b_setter.Address"> <property name="addr" value="海口"></property> <property name="tel" value="911"></property> </bean> <bean id="companyAddrId" class="com.itheima.f_xml.b_setter.Address"> <property name="addr" value="深圳"></property> <property name="tel" value="120"></property> </bean>
集合注入
<!-- 集合的注入都是给<property>添加子标签 数组:<array> List:<list> Set:<set> Map:<map> ,map存放k/v 键值对,使用<entry>描述 Properties:<props> <prop key=""></prop> 【】 普通数据:<value> 引用数据:<ref> --> <bean id="collDataId" class="com.itheima.f_xml.e_coll.CollData" > <property name="arrayData"> <array> <value>DS</value> <value>DZD</value> <value>露西</value> <value>莉莉</value> </array> </property> <property name="listData"> <list> <value>黑泽明</value> <value>宫崎骏</value> <value>小野丽莎</value> <value>苍井空</value> </list> </property> <property name="setData"> <set> <value>深圳</value> <value>广州</value> <value>东莞</value> </set> </property> <property name="mapData"> <map> <entry key="jack" value="茜茜公主"></entry> <entry> <key><value>rose</value></key> <value>白雪公主</value> </entry> </map> </property> <property name="propsData"> <props> <prop key="高富帅">嫐</prop> <prop key="白富美">嬲</prop> <prop key="男屌丝">挊</prop> </props> </property> </bean>
相关文章推荐
- 【JavaWeb-23】spring、IoC控制反转和DI依赖注入入门、基于XML的Bean装配、基于注解的Bean装配
- spring、IoC控制反转和DI依赖注入入门、基于XML的Bean装配、基于注解的Bean装配
- spring ioc容器注入的集中方式,以及属性注入的集中依赖,继承,使用SPEL表达式,ioc容器的生命周期,bean的几种工厂方法配置方式,bean的自动装配
- 框架 day36 Spring3 入门,DI依赖注入,装配bean基于xml/注解, 整合Junit4,配置约束自动提示
- 六、基于xml的bean实例化和依赖注入
- [原创]java WEB学习笔记99:Spring学习---Spring Bean配置:自动装配,配置bean之间的关系(继承/依赖),bean的作用域(singleton,prototype,web环境作用域),使用外部属性文件
- 基于Spring4的Bean的装配和依赖注入
- [Java] Spring 3.0 /id.vs.name/简单属性的注入/bean中的scope属性/集合注入/自动装配/生命周期/
- Spring4深入理解IOC&DI04----Bean配置方式(全类名,工厂方法,FactoryBean),配置形式(基于XML和注解),泛型依赖注入
- (spring-第3回【IoC基础篇】)spring的依赖注入-属性、构造函数、工厂方法等的注入(基于XML)
- 【Spring】使用XML进行Bean装配与依赖注入
- [Java] Spring 3.0 /id.vs.name/简单属性的注入/bean中的scope属性/集合注入/自动装配/生命周期/
- 用spring的注解建立bean与bean之间的关系组件装配及自动注入依赖对象
- 使用XPath解析xml实现简单的Spring IOC完成bean的依赖注入
- Spring依赖注入 — 属性自动装配
- 一个和spring整合的依赖注入的servlet,子类可自动装配依赖Bean
- 7.9.1: 容器中Bean的生命周期---依赖关系注入之后的行为
- 依赖注入Bean属性
- 【Java.Spring.Core】【IoC】基于注解的Bean装配(非XML配置)
- 11级_Java_曹建波 04.24 Spring的配置、生命周期、依赖注入bean的操作