spring装配Bean(基于xml)

转自:http://blog.csdn.net/csdn_gia/article/details/54730027


一、实例化方式

1、默认构造

<bean id="" class="">  必须提供默认构造

l  在spring容器中配置

[html] view plain copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.        xmlns:p="http://www.springframework.org/schema/p"  
  4.        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  5.        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">  
  6.   
  7.     <!--2  第一种方式 默认构造 -->  
  8.     <bean id="demo1User" class="cn.itcast.b_xmlbean.demo1.User"></bean>  
  9.       
  10. </beans>  

测试:
[java] view plain copy
  1. public static void main(String[] args) {  
  2.           
  3.         ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");  
  4.         User user = (User)applicationContext.getBean("demo1User");  
  5.           
  6.         System.out.println(user);  
  7.           
  8.           
  9. }  


2、静态工厂

l  常用与spring整合其他框架(工具)

l  静态工厂:用于生产实例对象,所有的方法必须是static

<bean id=""  class="工厂全限定类名" factory-method="静态方法">

UserService:
[java] view plain copy
  1. package com.itheima.c_inject.b_static_factory;  
  2.   
  3. public interface UserService {  
  4.       
  5.     public void addUser();  
  6.   
  7. }  


UserServiceImpl:
[java] view plain copy
  1. package com.itheima.c_inject.b_static_factory;  
  2.   
  3. public class UserServiceImpl implements UserService {  
  4.   
  5.     @Override  
  6.     public void addUser() {  
  7.         System.out.println("b_static_factory add user");  
  8.     }  
  9.   
  10. }  



beans.xml:
[html] view plain copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.        xsi:schemaLocation="http://www.springframework.org/schema/beans   
  5.                            http://www.springframework.org/schema/beans/spring-beans.xsd">  
  6.     <!-- 将静态工厂创建的实例交予spring   
  7.         class 确定静态工厂全限定类名  
  8.         factory-method 确定静态方法名  
  9.     -->  
  10.     <bean id="userServiceId" class="com.itheima.c_inject.b_static_factory.MyBeanFactory" factory-method="createService"></bean>  
  11.   
  12. </beans>  


MyBeanFactory:
[java] view plain copy
  1. package com.itheima.c_inject.b_static_factory;  
  2.   
  3. public class MyBeanFactory {  
  4.       
  5.     /** 
  6.      * 创建实例 
  7.      * @return 
  8.      */  
  9.     public static UserService createService(){  
  10.         return new UserServiceImpl();  
  11.     }  
  12.   
  13. }  


Test:
[java] view plain copy
  1. package com.itheima.c_inject.b_static_factory;  
  2.   
  3. import org.junit.Test;  
  4. import org.springframework.context.ApplicationContext;  
  5. import org.springframework.context.support.ClassPathXmlApplicationContext;  
  6.   
  7. /** 
  8.  * 静态工厂 
  9.  * 
  10.  */  
  11. public class TestStaticFactory {  
  12.       
  13.     @Test  
  14.     public void demo01(){  
  15.         //自定义工厂  
  16.         UserService userService = MyBeanFactory.createService();  
  17.         userService.addUser();  
  18.     }  
  19.     @Test  
  20.     public void demo02(){  
  21.         //spring 工厂  
  22.         String xmlPath = "com/itheima/c_inject/b_static_factory/beans.xml";  
  23.         ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);  
  24.         UserService userService = applicationContext.getBean("userServiceId" ,UserService.class);  
  25.         userService.addUser();  
  26.     }  
  27.   
  28. }  


3、实例工厂

l  实例工厂:必须先有工厂实例对象,通过实例对象创建对象。提供所有的方法都是“非静态”的。


UserService:
[java] view plain copy
  1. package com.itheima.c_inject.c_factory;  
  2.   
  3. public interface UserService {  
  4.       
  5.     public void addUser();  
  6.   
  7. }  


UserServiceImpl:
[java] view plain copy
  1. package com.itheima.c_inject.c_factory;  
  2.   
  3. public class UserServiceImpl implements UserService {  
  4.   
  5.     @Override  
  6.     public void addUser() {  
  7.         System.out.println("c_factory add user");  
  8.     }  
  9.   
  10. }  



MyBeanFactory:
[java] view plain copy
  1. package com.itheima.c_inject.c_factory;  
  2.   
  3. /** 
  4.  * 实例工厂,所有方法非静态 
  5.  * 
  6.  */  
  7. public class MyBeanFactory {  
  8.       
  9.     /** 
  10.      * 创建实例 
  11.      * @return 
  12.      */  
  13.     public UserService createService(){  
  14.         return new UserServiceImpl();  
  15.     }  
  16.   
  17. }  


beans.xml:
[html] view plain copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.        xsi:schemaLocation="http://www.springframework.org/schema/beans   
  5.                            http://www.springframework.org/schema/beans/spring-beans.xsd">  
  6.     <!-- 创建工厂实例 -->  
  7.     <bean id="myBeanFactoryId" class="com.itheima.c_inject.c_factory.MyBeanFactory"></bean>  
  8.     <!-- 获得userservice   
  9.         * factory-bean 确定工厂实例  
  10.         * factory-method 确定普通方法  
  11.     -->  
  12.     <bean id="userServiceId" factory-bean="myBeanFactoryId" factory-method="createService"></bean>  
  13.       
  14. </beans>  
spring装配Bean(基于xml)



Test:
[java] view plain copy
  1. package com.itheima.c_inject.c_factory;  
  2.   
  3. import org.junit.Test;  
  4. import org.springframework.context.ApplicationContext;  
  5. import org.springframework.context.support.ClassPathXmlApplicationContext;  
  6.   
  7. public class TestFactory {  
  8.       
  9.     @Test  
  10.     public void demo01(){  
  11.         //自定义实例工厂  
  12.         //1 创建工厂  
  13.         MyBeanFactory myBeanFactory = new MyBeanFactory();  
  14.         //2 通过工厂实例,获得对象  
  15.         UserService userService = myBeanFactory.createService();  
  16.           
  17.         userService.addUser();  
  18.     }  
  19.     @Test  
  20.     public void demo02(){  
  21.         //spring 工厂  
  22.         String xmlPath = "com/itheima/c_inject/c_factory/beans.xml";  
  23.         ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);  
  24.         UserService userService = applicationContext.getBean("userServiceId" ,UserService.class);  
  25.         userService.addUser();  
  26.     }  
  27.   
  28. }  


二、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实例个数

spring装配Bean(基于xml)

l  取值:

       singleton 单例,默认值。

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


l  配置信息

<bean id="" class=""  scope="">

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


UserService:

[java] view plain copy
  1. package com.itheima.d_scope;  
  2.   
  3. public interface UserService {  
  4.       
  5.     public void addUser();  
  6.   
  7. }  


UserServiceImpl:

[java] view plain copy
  1. package com.itheima.d_scope;  
  2.   
  3. public class UserServiceImpl implements UserService {  
  4.   
  5.     @Override  
  6.     public void addUser() {  
  7.         System.out.println("d_scope add user");  
  8.     }  
  9.   
  10. }  

beans.xml:

[html] view plain copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.        xsi:schemaLocation="http://www.springframework.org/schema/beans   
  5.                            http://www.springframework.org/schema/beans/spring-beans.xsd">  
  6.   
  7.     <bean id="userServiceId" class="com.itheima.d_scope.UserServiceImpl"   
  8.         scope="prototype" ></bean>  
  9.       
  10. </beans>  

TestScope:

[java] view plain copy
  1. package scope;  
  2.   
  3. import org.junit.Test;  
  4. import org.springframework.context.ApplicationContext;  
  5. import org.springframework.context.support.ClassPathXmlApplicationContext;  
  6.   
  7. public class TestScope {  
  8.       
  9.     @Test  
  10.     public void demo01(){  
  11.           
  12.         String xmlPath = "scope/beans.xml";  
  13.         ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);  
  14.           
  15.         UserService userService1 = applicationContext.getBean("userServiceId", UserService.class);  
  16.         UserService userService2 = applicationContext.getBean("userServiceId", UserService.class);  
  17.       
  18.         System.out.println(userService1);  
  19.         System.out.println(userService2);  
  20.       
  21.     }  
  22.   
  23. }  


四、生命周期

1、初始化和销毁

l  目标方法执行前和执行后,将进行初始化或销毁。

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


UserService:
[java] view plain copy
  1. package com.itheima.e_lifecycle;  
  2.   
  3. public interface UserService {  
  4.       
  5.     public void addUser();  
  6.   
  7. }  


UserServiceImpl:
[java] view plain copy
  1. package com.itheima.e_lifecycle;  
  2.   
  3. public class UserServiceImpl implements UserService {  
  4.   
  5.     @Override  
  6.     public void addUser() {  
  7.         System.out.println("e_lifecycle add user");  
  8.     }  
  9.       
  10.     public void myInit(){  
  11.         System.out.println("初始化");  
  12.     }  
  13.     public void myDestroy(){  
  14.         System.out.println("销毁");  
  15.     }  
  16.   
  17. }  



beans.xml:
[html] view plain copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.        xsi:schemaLocation="http://www.springframework.org/schema/beans   
  5.                            http://www.springframework.org/schema/beans/spring-beans.xsd">  
  6.   
  7.     <!--    
  8.         init-method 用于配置初始化方法,准备数据等  
  9.         destroy-method 用于配置销毁方法,清理资源等  
  10.     -->  
  11.     <bean id="userServiceId" class="com.itheima.e_lifecycle.UserServiceImpl"   
  12.         init-method="myInit" destroy-method="myDestroy" ></bean>  
  13.   
  14. </beans>  



TestCycle:
[java] view plain copy
  1. package com.itheima.e_lifecycle;  
  2.   
  3. import org.junit.Test;  
  4. import org.springframework.context.support.ClassPathXmlApplicationContext;  
  5.   
  6. public class TestCycle {  
  7.       
  8.     @Test  
  9.     public void demo02() throws Exception{  
  10.         //spring 工厂  
  11.         String xmlPath = "com/itheima/e_lifecycle/beans.xml";  
  12.         ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);  
  13.         UserService userService = (UserService) applicationContext.getBean("userServiceId");  
  14.         userService.addUser();  
  15.           
  16.         //要求:1.容器必须close,销毁方法执行; 2.必须是单例的  
  17. //      applicationContext.getClass().getMethod("close").invoke(applicationContext);  
  18.         // * 此方法接口中没有定义,实现类提供  
  19.         applicationContext.close();  
  20.           
  21.     }  
  22.   
  23. }  


2、BeanPostProcessor后处理Bean

l  spring 提供一种机制,只要实现此接口BeanPostProcessor,并将实现类提供给spring容器,

spring容器将自动执行,在初始化方法前执行before(),在初始化方法后执行after() 。 

配置<bean class="">

spring装配Bean(基于xml)

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:

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

beans.xml:

[html] view plain copy
  1. <!-- 将后处理的实现类注册给spring -->  
  2.     <bean class="com.itheima.e_lifecycle.MyBeanPostProcessor"></bean>  



l  问题1:后处理bean作用某一个目标类,还是所有目标类?

       所有

l  问题2:如何只作用一个?

       通过“参数2”beanName进行控制

[java] view plain copy
  1. @Override  
  2.     public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {  
  3.         if("userServiceId".equals(beanName)){  
  4.             System.out.println("前方法 : " + beanName);  
  5.         }  
  6.         return bean;  
  7.     }  


五、属性依赖注入

l  依赖注入方式:手动装配 和 自动装配

l  手动装配:一般进行配置信息都采用手动

       基于xml装配:构造方法、setter方法

       基于注解装配:

l  自动装配:struts和spring 整合可以自动装配

       byType:按类型装配

       byName:按名称装配

       constructor构造装配,

       auto: 不确定装配。


1、构造方法

User:
[java] view plain copy
  1. package com.itheima.f_xml.a_constructor;  
  2.   
  3. public class User {  
  4.       
  5.     private Integer uid;  
  6.     private String username;  
  7.     private Integer age;  
  8.       
  9.     public User(Integer uid, String username) {  
  10.         super();  
  11.         this.uid = uid;  
  12.         this.username = username;  
  13.     }  
  14.       
  15.     public User(String username, Integer age) {  
  16.         super();  
  17.         this.username = username;  
  18.         this.age = age;  
  19.     }  
  20.       
  21.       
  22.       
  23.     public Integer getUid() {  
  24.         return uid;  
  25.     }  
  26.     public void setUid(Integer uid) {  
  27.         this.uid = uid;  
  28.     }  
  29.     public String getUsername() {  
  30.         return username;  
  31.     }  
  32.     public void setUsername(String username) {  
  33.         this.username = username;  
  34.     }  
  35.     public Integer getAge() {  
  36.         return age;  
  37.     }  
  38.     public void setAge(Integer age) {  
  39.         this.age = age;  
  40.     }  
  41.     @Override  
  42.     public String toString() {  
  43.         return "User [uid=" + uid + ", username=" + username + ", age=" + age + "]";  
  44.     }  
  45.       
  46.       
  47.       
  48.       
  49.       
  50.   
  51. }  


beans.xml:
[html] view plain copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.        xsi:schemaLocation="http://www.springframework.org/schema/beans   
  5.                            http://www.springframework.org/schema/beans/spring-beans.xsd">  
  6.   
  7.     <!-- 构造方法注入   
  8.         * <constructor-arg> 用于配置构造方法一个参数argument  
  9.             name :参数的名称  
  10.             value:设置普通数据  
  11.             ref:引用数据,一般是另一个bean id值  
  12.               
  13.             index :参数的索引号,从0开始 。如果只有索引,匹配到了多个构造方法时,默认使用第一个。  
  14.             type :确定参数类型  
  15.         例如:使用名称name  
  16.             <constructor-arg name="username" value="jack"></constructor-arg>  
  17.             <constructor-arg name="age" value="18"></constructor-arg>  
  18.         例如2:类型type 和  索引 index  
  19.             <constructor-arg index="0" type="java.lang.String" value="1"></constructor-arg>  
  20.             <constructor-arg index="1" type="java.lang.Integer" value="2"></constructor-arg>  
  21.     -->  
  22.     <bean id="userId" class="com.itheima.f_xml.a_constructor.User" >  
  23.         <constructor-arg index="0" type="java.lang.String" value="1"></constructor-arg>  
  24.         <constructor-arg index="1" type="java.lang.Integer" value="2"></constructor-arg>  
  25.     </bean>  
  26. </beans>  


TestCons:
[java] view plain copy
  1. package com.itheima.f_xml.a_constructor;  
  2.   
  3. import org.junit.Test;  
  4. import org.springframework.context.ApplicationContext;  
  5. import org.springframework.context.support.ClassPathXmlApplicationContext;  
  6.   
  7. public class TestCons {  
  8.       
  9.     @Test  
  10.     public void demo02() throws Exception{  
  11.         //spring 工厂  
  12.         String xmlPath = "com/itheima/f_xml/a_constructor/beans.xml";  
  13.         ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);  
  14.         User user = (User) applicationContext.getBean("userId");  
  15.         System.out.println(user);  
  16.     }  
  17.   
  18. }  


2、setter方法

Person:
[java] view plain copy
  1. package com.itheima.f_xml.b_setter;  
  2.   
  3. public class Person {  
  4.       
  5.     private String pname;  
  6.     private Integer age;  
  7.       
  8.     private Address homeAddr;       //家庭地址  
  9.     private Address companyAddr;    //公司地址  
  10.     public String getPname() {  
  11.         return pname;  
  12.     }  
  13.     public void setPname(String pname) {  
  14.         this.pname = pname;  
  15.     }  
  16.     public Integer getAge() {  
  17.         return age;  
  18.     }  
  19.     public void setAge(Integer age) {  
  20.         this.age = age;  
  21.     }  
  22.     public Address getHomeAddr() {  
  23.         return homeAddr;  
  24.     }  
  25.     public void setHomeAddr(Address homeAddr) {  
  26.         this.homeAddr = homeAddr;  
  27.     }  
  28.     public Address getCompanyAddr() {  
  29.         return companyAddr;  
  30.     }  
  31.     public void setCompanyAddr(Address companyAddr) {  
  32.         this.companyAddr = companyAddr;  
  33.     }  
  34.     @Override  
  35.     public String toString() {  
  36.         return "Person [pname=" + pname + ", age=" + age + ", homeAddr=" + homeAddr + ", companyAddr=" + companyAddr + "]";  
  37.     }  
  38.   
  39.       
  40.       
  41. }  



Address:
[java] view plain copy
  1. package com.itheima.f_xml.b_setter;  
  2.   
  3. public class Address {  
  4.       
  5.     private String addr;    //地址信息  
  6.     private String tel;     //电话  
  7.       
  8.       
  9.     public String getAddr() {  
  10.         return addr;  
  11.     }  
  12.     public void setAddr(String addr) {  
  13.         this.addr = addr;  
  14.     }  
  15.     public String getTel() {  
  16.         return tel;  
  17.     }  
  18.     public void setTel(String tel) {  
  19.         this.tel = tel;  
  20.     }  
  21.     @Override  
  22.     public String toString() {  
  23.         return "Address [addr=" + addr + ", tel=" + tel + "]";  
  24.     }  
  25.       
  26.       
  27.   
  28. }  


beans.xml:
[html] view plain copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.        xsi:schemaLocation="http://www.springframework.org/schema/beans   
  5.                            http://www.springframework.org/schema/beans/spring-beans.xsd">  
  6.       
  7.     <!-- setter方法注入   
  8.         * 普通数据   
  9.             <property name="" value="值">  
  10.             等效  
  11.             <property name="">  
  12.                 <value></value>  
  13.         * 引用数据  
  14.             <property name="" ref="另一个bean">  
  15.             等效  
  16.             <property name="">  
  17.                 <ref bean="另一个bean"/>  
  18.       
  19.     -->  
  20.     <bean id="personId" class="com.itheima.f_xml.b_setter.Person">  
  21.         <property name="pname" value="阳志"></property>  
  22.         <property name="age">  
  23.             <value>1234</value>  
  24.         </property>  
  25.           
  26.         <property name="homeAddr" ref="homeAddrId"></property>  
  27.         <property name="companyAddr">  
  28.             <ref bean="companyAddrId"/>  
  29.         </property>  
  30.     </bean>  
  31.       
  32.     <bean id="homeAddrId" class="com.itheima.f_xml.b_setter.Address">  
  33.         <property name="addr" value="阜南"></property>  
  34.         <property name="tel" value="911"></property>  
  35.     </bean>  
  36.     <bean id="companyAddrId" class="com.itheima.f_xml.b_setter.Address">  
  37.         <property name="addr" value="北京八宝山"></property>  
  38.         <property name="tel" value="120"></property>  
  39.     </bean>  
  40.       
  41. </beans>  



TestSetter:
[java] view plain copy
  1. package com.itheima.f_xml.b_setter;  
  2.   
  3. import org.junit.Test;  
  4. import org.springframework.beans.factory.BeanFactory;  
  5. import org.springframework.beans.factory.xml.XmlBeanFactory;  
  6. import org.springframework.context.ApplicationContext;  
  7. import org.springframework.context.support.ClassPathXmlApplicationContext;  
  8. import org.springframework.core.io.ClassPathResource;  
  9. import org.springframework.core.io.Resource;  
  10.   
  11. public class TestSetter {  
  12.       
  13.     @Test  
  14.     public void demo01(){  
  15.         //从spring容器获得  
  16.         String xmlPath = "com/itheima/f_xml/b_setter/beans.xml";  
  17.         ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);  
  18.         Person person = (Person) applicationContext.getBean("personId");  
  19.           
  20.         System.out.println(person);  
  21.           
  22.     }  
  23.   
  24. }  



3、P命令空间

l  对“setter方法注入”进行简化,替换<property name="属性名">,而是在

       <beanp:属性名="普通值"  p:属性名-ref="引用值">

l  p命名空间使用前提,必须添加命名空间

spring装配Bean(基于xml)

beans.xml:
[html] view plain copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.        xmlns:p="http://www.springframework.org/schema/p"  
  5.        xsi:schemaLocation="http://www.springframework.org/schema/beans   
  6.                            http://www.springframework.org/schema/beans/spring-beans.xsd">  
  7.       
  8.     <bean id="personId" class="com.itheima.f_xml.c_p.Person"   
  9.         p:pname="禹太璞" p:age="22"   
  10.         p:homeAddr-ref="homeAddrId" p:companyAddr-ref="companyAddrId">  
  11.     </bean>  
  12.       
  13.     <bean id="homeAddrId" class="com.itheima.f_xml.c_p.Address"  
  14.         p:addr="DG" p:tel="东莞">  
  15.     </bean>  
  16.     <bean id="companyAddrId" class="com.itheima.f_xml.c_p.Address"  
  17.         p:addr="DG" p:tel="岛国">  
  18.     </bean>  
  19.       
  20. </beans>  


4、SpEL

l  对<property>进行统一编程,所有的内容都使用value

       <propertyname="" value="#{表达式}">

       #{123}、#{'jack'} : 数字、字符串

       #{beanId}      :另一个bean引用     

       #{beanId.propName}     :操作数据

       #{beanId.toString()}     :执行方法

       #{T(类).字段|方法}      :静态方法或字段


Customer:
[java] view plain copy
  1. package com.itheima.f_xml.d_spel;  
  2.   
  3. public class Customer {  
  4.       
  5.     private String cname = "jack";  
  6.     private Double pi ;// = Math.PI;  
  7.     public String getCname() {  
  8.         return cname;  
  9.     }  
  10.     public void setCname(String cname) {  
  11.         this.cname = cname;  
  12.     }  
  13.     public Double getPi() {  
  14.         return pi;  
  15.     }  
  16.     public void setPi(Double pi) {  
  17.         this.pi = pi;  
  18.     }  
  19.     @Override  
  20.     public String toString() {  
  21.         return "Customer [cname=" + cname + ", pi=" + pi + "]";  
  22.     }  
  23.       
  24.   
  25. }  



beans.xml:
[html] view plain copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.        xsi:schemaLocation="http://www.springframework.org/schema/beans   
  5.                            http://www.springframework.org/schema/beans/spring-beans.xsd">  
  6.   
  7.     <!--   
  8.         <property name="cname" value="#{'jack'}"></property>  
  9.         <property name="cname" value="#{customerId.cname.toUpperCase()}"></property>  
  10.             通过另一个bean,获得属性,调用的方法  
  11.         <property name="cname" value="#{customerId.cname?.toUpperCase()}"></property>  
  12.             ?.  如果对象不为null,将调用方法  
  13.     -->  
  14.     <bean id="customerId" class="com.itheima.f_xml.d_spel.Customer" >  
  15.         <property name="cname" value="#{customerId.cname?.toUpperCase()}"></property>  
  16.         <property name="pi" value="#{T(java.lang.Math).PI}"></property>  
  17.     </bean>  
  18. </beans>  



TestSpEL:
[java] view plain copy
  1. package com.itheima.f_xml.d_spel;  
  2.   
  3. import org.junit.Test;  
  4. import org.springframework.context.ApplicationContext;  
  5. import org.springframework.context.support.ClassPathXmlApplicationContext;  
  6.   
  7. public class TestSpEL {  
  8.       
  9.     @Test  
  10.     public void demo02() throws Exception{  
  11.         //spring 工厂  
  12.         String xmlPath = "com/itheima/f_xml/d_spel/beans.xml";  
  13.         ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);  
  14.         Customer customer = (Customer) applicationContext.getBean("customerId");  
  15.         System.out.println(customer);  
  16.     }  
  17.   
  18. }  

5、集合注入

CollData:
[java] view plain copy
  1. package com.itheima.f_xml.e_coll;  
  2.   
  3. import java.util.Arrays;  
  4. import java.util.List;  
  5. import java.util.Map;  
  6. import java.util.Properties;  
  7. import java.util.Set;  
  8.   
  9. public class CollData {  
  10.       
  11.     private String[] arrayData;  
  12.     private List<String> listData;  
  13.     private Set<String> setData;  
  14.     private Map<String, String> mapData;  
  15.     private Properties propsData;  
  16.     public String[] getArrayData() {  
  17.         return arrayData;  
  18.     }  
  19.     public void setArrayData(String[] arrayData) {  
  20.         this.arrayData = arrayData;  
  21.     }  
  22.     public List<String> getListData() {  
  23.         return listData;  
  24.     }  
  25.     public void setListData(List<String> listData) {  
  26.         this.listData = listData;  
  27.     }  
  28.     public Set<String> getSetData() {  
  29.         return setData;  
  30.     }  
  31.     public void setSetData(Set<String> setData) {  
  32.         this.setData = setData;  
  33.     }  
  34.     public Map<String, String> getMapData() {  
  35.         return mapData;  
  36.     }  
  37.     public void setMapData(Map<String, String> mapData) {  
  38.         this.mapData = mapData;  
  39.     }  
  40.     public Properties getPropsData() {  
  41.         return propsData;  
  42.     }  
  43.     public void setPropsData(Properties propsData) {  
  44.         this.propsData = propsData;  
  45.     }  
  46.     @Override  
  47.     public String toString() {  
  48.         return "CollData [\narrayData=" + Arrays.toString(arrayData) + ", \nlistData=" + listData + ", \nsetData=" + setData + ", \nmapData=" + mapData + ", \npropsData=" + propsData + "\n]";  
  49.     }  
  50.       
  51.       
  52. }  



beans.xml:
[html] view plain copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.        xsi:schemaLocation="http://www.springframework.org/schema/beans   
  5.                            http://www.springframework.org/schema/beans/spring-beans.xsd">  
  6.   
  7.     <!--   
  8.         集合的注入都是给<property>添加子标签  
  9.             数组:<array>  
  10.             List:<list>  
  11.             Set:<set>  
  12.             Map:<map> ,map存放k/v 键值对,使用<entry>描述  
  13.             Properties:<props>  <prop key=""></prop>  【】  
  14.               
  15.         普通数据:<value>  
  16.         引用数据:<ref>  
  17.     -->  
  18.     <bean id="collDataId" class="com.itheima.f_xml.e_coll.CollData" >  
  19.         <property name="arrayData">  
  20.             <array>  
  21.                 <value>DS</value>  
  22.                 <value>DZD</value>  
  23.                 <value>屌丝</value>  
  24.                 <value>屌中屌</value>  
  25.             </array>  
  26.         </property>  
  27.           
  28.         <property name="listData">  
  29.             <list>  
  30.                 <value>于嵩楠</value>  
  31.                 <value>曾卫</value>  
  32.                 <value>杨煜</value>  
  33.                 <value>曾小贤</value>  
  34.             </list>  
  35.         </property>  
  36.           
  37.         <property name="setData">  
  38.             <set>  
  39.                 <value>停封</value>  
  40.                 <value>薄纸</value>  
  41.                 <value>关系</value>  
  42.             </set>  
  43.         </property>  
  44.           
  45.         <property name="mapData">  
  46.             <map>  
  47.                 <entry key="jack" value="杰克"></entry>  
  48.                 <entry>  
  49.                     <key><value>rose</value></key>  
  50.                     <value>肉丝</value>  
  51.                 </entry>  
  52.             </map>  
  53.         </property>  
  54.           
  55.         <property name="propsData">  
  56.             <props>  
  57.                 <prop key="高富帅"></prop>  
  58.                 <prop key="白富美"></prop>  
  59.                 <prop key="男屌丝"></prop>  
  60.             </props>  
  61.         </property>  
  62.     </bean>  
  63. </beans>  



TestColl:
[java] view plain copy
  1. package com.itheima.f_xml.e_coll;  
  2.   
  3. import org.junit.Test;  
  4. import org.springframework.context.ApplicationContext;  
  5. import org.springframework.context.support.ClassPathXmlApplicationContext;  
  6.   
  7. public class TestColl {  
  8.       
  9.     @Test  
  10.     public void demo02() throws Exception{  
  11.         //spring 工厂  
  12.         String xmlPath = "com/itheima/f_xml/e_coll/beans.xml";  
  13.         ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);  
  14.         CollData collData = (CollData) applicationContext.getBean("collDataId");  
  15.         System.out.println(collData);  
  16.     }  
  17.   
  18. }