spring裝配Bean(基於xml)

裝配Bean(基於xml)

一、例項化方式

1、預設構造

<bean id=”” class=””>  必須提供預設構造

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=”靜態方法”>

UserService:
package com.itheima.c_inject.b_static_factory;
public interface UserService {
public void addUser();
}
UserServiceImpl:
package com.itheima.c_inject.b_static_factory;
public class UserServiceImpl implements UserService {
@Override
public void addUser() {
System.out.println("b_static_factory 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">
<!-- 將靜態工廠建立的例項交予spring 
class 確定靜態工廠全限定類名
factory-method 確定靜態方法名
-->
<bean id="userServiceId" class="com.itheima.c_inject.b_static_factory.MyBeanFactory" factory-method="createService"></bean>
</beans>
MyBeanFactory:
package com.itheima.c_inject.b_static_factory;
public class MyBeanFactory {
/**
* 建立例項
* @return
*/
public static UserService createService(){
return new UserServiceImpl();
}
}
Test:
package com.itheima.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/itheima/c_inject/b_static_factory/beans.xml";
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
UserService userService = applicationContext.getBean("userServiceId" ,UserService.class);
userService.addUser();
}
}

3、例項工廠

l  例項工廠:必須先有工廠例項物件,通過例項物件建立物件。提供所有的方法都是“非靜態”的。

UserService:
package com.itheima.c_inject.c_factory;
public interface UserService {
public void addUser();
}

UserServiceImpl:
package com.itheima.c_inject.c_factory;
public class UserServiceImpl implements UserService {
@Override
public void addUser() {
System.out.println("c_factory add user");
}
}
MyBeanFactory:
package com.itheima.c_inject.c_factory;
/**
* 例項工廠,所有方法非靜態
*
*/
public class MyBeanFactory {
/**
* 建立例項
* @return
*/
public UserService createService(){
return new UserServiceImpl();
}
}

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="myBeanFactoryId" class="com.itheima.c_inject.c_factory.MyBeanFactory"></bean>
<!-- 獲得userservice 
* factory-bean 確定工廠例項
* factory-method 確定普通方法
-->
<bean id="userServiceId" factory-bean="myBeanFactoryId" factory-method="createService"></bean>
</beans>

Test:
package com.itheima.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/itheima/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例項個數

l  取值:

       singleton 單例,預設值。

       prototype 多例,每執行一次getBean將獲得一個例項。例如:struts整合spring,配置action多例。

l  配置資訊

<bean id=”” class=””  scope=””>

<beanid=“userServiceId”class=“com.itheima.d_scope.UserServiceImpl”  scope=“prototype”></bean>

UserService:

package com.itheima.d_scope;
public interface UserService {
public void addUser();
}

UserServiceImpl:

package com.itheima.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.itheima.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.itheima.e_lifecycle;
public interface UserService {
public void addUser();
}

UserServiceImpl:
package com.itheima.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("銷燬");
}
}
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">
<!--  
init-method 用於配置初始化方法,準備資料等
destroy-method 用於配置銷燬方法,清理資源等
-->
<bean id="userServiceId" class="com.itheima.e_lifecycle.UserServiceImpl" 
init-method="myInit" destroy-method="myDestroy" ></bean>
</beans>
TestCycle:
package com.itheima.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/itheima/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.itheima.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.itheima.e_lifecycle.MyBeanPostProcessor"></bean>

l  問題1:後處理bean作用某一個目標類,還是所有目標類?

       所有

l  問題2:如何只作用一個?

       通過“引數2”beanName進行控制

@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if("userServiceId".equals(beanName)){
System.out.println("前方法 : "   beanName);
}
return bean;
}

五、屬性依賴注入

l  依賴注入方式:手動裝配 和 自動裝配

l  手動裝配:一般進行配置資訊都採用手動

       基於xml裝配:構造方法、setter方法

       基於註解裝配:

l  自動裝配:struts和spring 整合可以自動裝配

       byType:按型別裝配

       byName:按名稱裝配

       constructor構造裝配,

       auto: 不確定裝配。

1、構造方法

User:
package com.itheima.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.itheima.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>
TestCons:
package com.itheima.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/itheima/f_xml/a_constructor/beans.xml";
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
User user = (User) applicationContext.getBean("userId");
System.out.println(user);
}
}

2、setter方法

Person:
package com.itheima.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   "]";
}
}
Address:
package com.itheima.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.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>
</beans>
TestSetter:
package com.itheima.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/itheima/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名稱空間使用前提,必須新增名稱空間

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"
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.itheima.f_xml.c_p.Person" 
p:pname="禹太璞" p:age="22" 
p:homeAddr-ref="homeAddrId" p:companyAddr-ref="companyAddrId">
</bean>
<bean id="homeAddrId" class="com.itheima.f_xml.c_p.Address"
p:addr="DG" p:tel="東莞">
</bean>
<bean id="companyAddrId" class="com.itheima.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(類).欄位|方法}      :靜態方法或欄位

Customer:
package com.itheima.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   "]";
}
}
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">
<!-- 
<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.itheima.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>
TestSpEL:
package com.itheima.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/itheima/f_xml/d_spel/beans.xml";
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
Customer customer = (Customer) applicationContext.getBean("customerId");
System.out.println(customer);
}
}

5、集合注入

CollData:
package com.itheima.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]";
}
}
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">
<!-- 
集合的注入都是給<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>
</beans>
TestColl:
package com.itheima.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/itheima/f_xml/e_coll/beans.xml";
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
CollData collData = (CollData) applicationContext.getBean("collDataId");
System.out.println(collData);
}
}