装配Bean(基于xml)
一、实例化方式
1、默认构造
l 在spring容器中配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p"
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">
<!--2 第一种方式 默认构造 -->
<bean id="demo1User" class="cn.itcast.b_xmlbean.demo1.User"></bean>
</beans>
测试:
public static void main(String[] args) {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
User user = (User)applicationContext.getBean("demo1User");
System.out.println(user);
}
2、静态工厂
l 常用与spring整合其他框架(工具)
l 静态工厂:用于生产实例对象,所有的方法必须是static
<bean id="" class="工厂全限定类名" factory-method="静态方法">package com.hcx.c_inject.b_static_factory;
public interface UserService {
public void addUser();
}
package com.hcx.c_inject.b_static_factory;
public class UserServiceImpl implements UserService {
@Override
public void addUser() {
System.out.println("b_static_factory add user");
}
}
<?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">
<!-- 将静态工厂创建的实例交予spring
class 确定静态工厂全限定类名
factory-method 确定静态方法名
-->
<bean id="userServiceId" class="com.hcx.c_inject.b_static_factory.MyBeanFactory" factory-method="createService"></bean>
</beans>
package com.hcx.c_inject.b_static_factory;
public class MyBeanFactory {
/**
* 创建实例
* @return
*/
public static UserService createService(){
return new UserServiceImpl();
}
}
package com.hcx.c_inject.b_static_factory;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* 静态工厂
*
*/
public class TestStaticFactory {
@Test
public void demo01(){
//自定义工厂
UserService userService = MyBeanFactory.createService();
userService.addUser();
}
@Test
public void demo02(){
//spring 工厂
String xmlPath = "com/hcx/c_inject/b_static_factory/beans.xml";
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
UserService userService = applicationContext.getBean("userServiceId" ,UserService.class);
userService.addUser();
}
}
3、实例工厂
l 实例工厂:必须先有工厂实例对象,通过实例对象创建对象。提供所有的方法都是“非静态”的。
package com.hcx.c_inject.c_factory;
public interface UserService {
public void addUser();
}
package com.hcx.c_inject.c_factory;
public class UserServiceImpl implements UserService {
@Override
public void addUser() {
System.out.println("c_factory add user");
}
}
package com.hcx.c_inject.c_factory;
/**
* 实例工厂,所有方法非静态
*
*/
public class MyBeanFactory {
/**
* 创建实例
* @return
*/
public UserService createService(){
return new UserServiceImpl();
}
}
<?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="myBeanFactoryId" class="com.hcx.c_inject.c_factory.MyBeanFactory"></bean>
<!-- 获得userservice
* factory-bean 确定工厂实例
* factory-method 确定普通方法
-->
<bean id="userServiceId" factory-bean="myBeanFactoryId" factory-method="createService"></bean>
</beans>
![](https://i-blog.csdnimg.cn/blog_migrate/9e2eea5f4fd2505e1b3843f90183aec0.png)
package com.hcx.c_inject.c_factory;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestFactory {
@Test
public void demo01(){
//自定义实例工厂
//1 创建工厂
MyBeanFactory myBeanFactory = new MyBeanFactory();
//2 通过工厂实例,获得对象
UserService userService = myBeanFactory.createService();
userService.addUser();
}
@Test
public void demo02(){
//spring 工厂
String xmlPath = "com/hcx/c_inject/c_factory/beans.xml";
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
UserService userService = applicationContext.getBean("userServiceId" ,UserService.class);
userService.addUser();
}
}
二、bean种类
l 普通bean:
之前操作的都是普通bean。<bean id="" class="A"> ,spring直接创建A实例,并返回
l FactoryBean:
是一个特殊的bean,具有工厂生成对象能力,只能生成特定的对象。
bean必须使用 FactoryBean接口,此接口提供方法 getObject() 用于获得特定bean。
<bean id="" class="FB"> 先创建FB实例,使用调用getObject()方法,并返回方法的返回值
FB fb = new FB();
return fb.getObject();
l BeanFactory 和 FactoryBean 对比?
BeanFactory:工厂,用于生成任意bean。
FactoryBean:特殊bean,用于生成另一个特定的bean。例如:ProxyFactoryBean ,此工厂bean用于生产代理。
<bean id=""class="....ProxyFactoryBean"> 获得代理对象实例。AOP使用
三、作用域
l 作用域:用于确定spring创建bean实例个数
![](https://i-blog.csdnimg.cn/blog_migrate/d5e8bddd61ca10397ea059d1919779bf.png)
l 取值:
singleton 单例,默认值。
prototype 多例,每执行一次getBean将获得一个实例。例如:struts整合spring,配置action多例。
l 配置信息
<bean id="" class="" scope="">
<beanid="userServiceId"class="com.hcx.d_scope.UserServiceImpl" scope="prototype"></bean>
UserService:
package com.hcx.d_scope;
public interface UserService {
public void addUser();
}
UserServiceImpl:
package com.hcx.d_scope;
public class UserServiceImpl implements UserService {
@Override
public void addUser() {
System.out.println("d_scope add user");
}
}
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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="userServiceId" class="com.hcx.d_scope.UserServiceImpl"
scope="prototype" ></bean>
</beans>
TestScope:
package scope;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestScope {
@Test
public void demo01(){
String xmlPath = "scope/beans.xml";
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
UserService userService1 = applicationContext.getBean("userServiceId", UserService.class);
UserService userService2 = applicationContext.getBean("userServiceId", UserService.class);
System.out.println(userService1);
System.out.println(userService2);
}
}
四、生命周期
1、初始化和销毁
l 目标方法执行前和执行后,将进行初始化或销毁。
<bean id="" class="" init-method="初始化方法名称" destroy-method="销毁的方法名称"> |
UserService:
package com.hcx.e_lifecycle;
public interface UserService {
public void addUser();
}
package com.hcx.e_lifecycle;
public class UserServiceImpl implements UserService {
@Override
public void addUser() {
System.out.println("e_lifecycle add user");
}
public void myInit(){
System.out.println("初始化");
}
public void myDestroy(){
System.out.println("销毁");
}
}
<?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">
<!--
init-method 用于配置初始化方法,准备数据等
destroy-method 用于配置销毁方法,清理资源等
-->
<bean id="userServiceId" class="com.hcx.e_lifecycle.UserServiceImpl"
init-method="myInit" destroy-method="myDestroy" ></bean>
</beans>
package com.hcx.e_lifecycle;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestCycle {
@Test
public void demo02() throws Exception{
//spring 工厂
String xmlPath = "com/hcx/e_lifecycle/beans.xml";
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
UserService userService = (UserService) applicationContext.getBean("userServiceId");
userService.addUser();
//要求:1.容器必须close,销毁方法执行; 2.必须是单例的
// applicationContext.getClass().getMethod("close").invoke(applicationContext);
// * 此方法接口中没有定义,实现类提供
applicationContext.close();
}
}
2、BeanPostProcessor后处理Bean
l spring 提供一种机制,只要实现此接口BeanPostProcessor,并将实现类提供给spring容器,
spring容器将自动执行,在初始化方法前执行before(),在初始化方法后执行after() 。
配置<bean class="">
l Factory hook(勾子) that allows for custom modification of new bean instances, e.g.checking for marker interfaces or wrapping them with proxies.
l spring提供工厂勾子,用于修改实例对象,可以生成代理对象,是AOP底层。
模拟
A a =new A();
a = B.before(a) --> 当a的实例对象传递给后处理bean,可以生成代理对象并返回。
a.init();
a = B.after(a);
a.addUser(); //生成代理对象,目的在目标方法前后执行(例如:开启事务、提交事务)
a.destroy()
MyBeanPostProcessor:
package com.hcx.e_lifecycle;
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 {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.out.println("前方法 : " + beanName);
return bean;
}
@Override
public Object postProcessAfterInitialization(final Object bean, String beanName) throws BeansException {
System.out.println("后方法 : " + beanName);
// bean 目标对象
// 生成 jdk 代理
return Proxy.newProxyInstance(
MyBeanPostProcessor.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;
}});
}
}
beans.xml:
<!-- 将后处理的实现类注册给spring -->
<bean class="com.hcx.e_lifecycle.MyBeanPostProcessor"></bean>
问题1:后处理bean作用某一个目标类,还是所有目标类?
所有
问题2:如何只作用一个?
通过“参数2”beanName进行控制
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if("userServiceId".equals(beanName)){
System.out.println("前方法 : " + beanName);
}
return bean;
}
五、属性依赖注入
依赖注入方式:手动装配 和 自动装配
手动装配:一般进行配置信息都采用手动
- 基于xml装配:构造方法、setter方法
- 基于注解装配:
自动装配:struts和spring 整合可以自动装配
- byType:按类型装配
- byName:按名称装配
- constructor构造装配,
- auto: 不确定装配。
1、构造方法
package com.hcx.f_xml.a_constructor;
public class User {
private Integer uid;
private String username;
private Integer age;
public User(Integer uid, String username) {
super();
this.uid = uid;
this.username = username;
}
public User(String username, Integer age) {
super();
this.username = username;
this.age = age;
}
public Integer getUid() {
return uid;
}
public void setUid(Integer uid) {
this.uid = uid;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "User [uid=" + uid + ", username=" + username + ", age=" + age + "]";
}
}
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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- 构造方法注入
* <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.hcx.f_xml.a_constructor.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>
</beans>
package com.hcx.f_xml.a_constructor;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestCons {
@Test
public void demo02() throws Exception{
//spring 工厂
String xmlPath = "com/hcx/f_xml/a_constructor/beans.xml";
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
User user = (User) applicationContext.getBean("userId");
System.out.println(user);
}
}
2、setter方法
package com.hcx.f_xml.b_setter;
public class Person {
private String pname;
private Integer age;
private Address homeAddr; //家庭地址
private Address companyAddr; //公司地址
public String getPname() {
return pname;
}
public void setPname(String pname) {
this.pname = pname;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Address getHomeAddr() {
return homeAddr;
}
public void setHomeAddr(Address homeAddr) {
this.homeAddr = homeAddr;
}
public Address getCompanyAddr() {
return companyAddr;
}
public void setCompanyAddr(Address companyAddr) {
this.companyAddr = companyAddr;
}
@Override
public String toString() {
return "Person [pname=" + pname + ", age=" + age + ", homeAddr=" + homeAddr + ", companyAddr=" + companyAddr + "]";
}
}
package com.hcx.f_xml.b_setter;
public class Address {
private String addr; //地址信息
private String tel; //电话
public String getAddr() {
return addr;
}
public void setAddr(String addr) {
this.addr = addr;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
@Override
public String toString() {
return "Address [addr=" + addr + ", tel=" + tel + "]";
}
}
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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- setter方法注入
* 普通数据
<property name="" value="值">
等效
<property name="">
<value>值</value>
* 引用数据
<property name="" ref="另一个bean">
等效
<property name="">
<ref bean="另一个bean"/>
-->
<bean id="personId" class="com.hcx.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.hcx.f_xml.b_setter.Address">
<property name="addr" value="阜南"></property>
<property name="tel" value="911"></property>
</bean>
<bean id="companyAddrId" class="com.hcx.f_xml.b_setter.Address">
<property name="addr" value="北京八宝山"></property>
<property name="tel" value="120"></property>
</bean>
</beans>
package com.hcx.f_xml.b_setter;
import org.junit.Test;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
public class TestSetter {
@Test
public void demo01(){
//从spring容器获得
String xmlPath = "com/hcx/f_xml/b_setter/beans.xml";
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
Person person = (Person) applicationContext.getBean("personId");
System.out.println(person);
}
}
3、P命令空间
l 对“setter方法注入”进行简化,替换<property name="属性名">,而是在
<beanp:属性名="普通值" p:属性名-ref="引用值">
l p命名空间使用前提,必须添加命名空间
![](https://i-blog.csdnimg.cn/blog_migrate/701285d9c38def0996694336b11c73a4.png)
<?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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="personId" class="com.hcx.f_xml.c_p.Person"
p:pname="禹太璞" p:age="22"
p:homeAddr-ref="homeAddrId" p:companyAddr-ref="companyAddrId">
</bean>
<bean id="homeAddrId" class="com.hcx.f_xml.c_p.Address"
p:addr="DG" p:tel="东莞">
</bean>
<bean id="companyAddrId" class="com.hcx.f_xml.c_p.Address"
p:addr="DG" p:tel="岛国">
</bean>
</beans>
4、SpEL
l 对<property>进行统一编程,所有的内容都使用value
<propertyname="" value="#{表达式}">
#{123}、#{'jack'} : 数字、字符串
#{beanId} :另一个bean引用
#{beanId.propName} :操作数据
#{beanId.toString()} :执行方法
#{T(类).字段|方法} :静态方法或字段
package com.hcx.f_xml.d_spel;
public class Customer {
private String cname = "jack";
private Double pi ;// = Math.PI;
public String getCname() {
return cname;
}
public void setCname(String cname) {
this.cname = cname;
}
public Double getPi() {
return pi;
}
public void setPi(Double pi) {
this.pi = pi;
}
@Override
public String toString() {
return "Customer [cname=" + cname + ", pi=" + pi + "]";
}
}
<?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">
<!--
<property name="cname" value="#{'jack'}"></property>
<property name="cname" value="#{customerId.cname.toUpperCase()}"></property>
通过另一个bean,获得属性,调用的方法
<property name="cname" value="#{customerId.cname?.toUpperCase()}"></property>
?. 如果对象不为null,将调用方法
-->
<bean id="customerId" class="com.hcx.f_xml.d_spel.Customer" >
<property name="cname" value="#{customerId.cname?.toUpperCase()}"></property>
<property name="pi" value="#{T(java.lang.Math).PI}"></property>
</bean>
</beans>
package com.hcx.f_xml.d_spel;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestSpEL {
@Test
public void demo02() throws Exception{
//spring 工厂
String xmlPath = "com/hcx/f_xml/d_spel/beans.xml";
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
Customer customer = (Customer) applicationContext.getBean("customerId");
System.out.println(customer);
}
}
5、集合注入
package com.hcx.f_xml.e_coll;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
public class CollData {
private String[] arrayData;
private List<String> listData;
private Set<String> setData;
private Map<String, String> mapData;
private Properties propsData;
public String[] getArrayData() {
return arrayData;
}
public void setArrayData(String[] arrayData) {
this.arrayData = arrayData;
}
public List<String> getListData() {
return listData;
}
public void setListData(List<String> listData) {
this.listData = listData;
}
public Set<String> getSetData() {
return setData;
}
public void setSetData(Set<String> setData) {
this.setData = setData;
}
public Map<String, String> getMapData() {
return mapData;
}
public void setMapData(Map<String, String> mapData) {
this.mapData = mapData;
}
public Properties getPropsData() {
return propsData;
}
public void setPropsData(Properties propsData) {
this.propsData = propsData;
}
@Override
public String toString() {
return "CollData [\narrayData=" + Arrays.toString(arrayData) + ", \nlistData=" + listData + ", \nsetData=" + setData + ", \nmapData=" + mapData + ", \npropsData=" + propsData + "\n]";
}
}
<?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">
<!--
集合的注入都是给<property>添加子标签
数组:<array>
List:<list>
Set:<set>
Map:<map> ,map存放k/v 键值对,使用<entry>描述
Properties:<props> <prop key=""></prop> 【】
普通数据:<value>
引用数据:<ref>
-->
<bean id="collDataId" class="com.hcx.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>
</beans>
package com.hcx.f_xml.e_coll;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestColl {
@Test
public void demo02() throws Exception{
//spring 工厂
String xmlPath = "com/hcx/f_xml/e_coll/beans.xml";
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
CollData collData = (CollData) applicationContext.getBean("collDataId");
System.out.println(collData);
}
}