數組添加值
public class DiTest { /** * 數組 */ private String [] arrays; /** * List:集合 */ private List<Integer> lists; /** * Set: 無序集合 */ private Set<String> sets; /** * Map */ private Map<String,Object> maps; /** * 配置 */ private Properties properties;
首先先編寫一個applicationContextList.xml大配置文件
然后在到大配置里面配置實體類名
<bean id="diTest" class="com.wdkseft.entity.DiTest">
數組(arrays)
<!--數組--> <property name="arrays"> <array> <value>呵呵</value> <value>啦啦</value> </array> </property>
List
<!--list--> <property name="lists"> <list> <value>18</value> <value>19</value> </list> </property>
Set
<!--set--> <property name="sets"> <set> <value>ashdads</value> <value>ajfiasdj</value> </set> </property>
Map
<!--Map--> <property name="maps"> <map> <entry key="name" value="lll"></entry> <entry key="age" value="18"></entry> </map> </property>
properties
<!--properties--> <property name="properties"> <props> <prop key="jdbc.drver">com.mysql.jdbc.Driver</prop> <prop key="jdbc.username">root</prop> </props> </property>
單步執行
@Test
public void List(){
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContextList.xml");
DiTest diTest = (DiTest) ctx.getBean("diTest");
System.out.println(diTest.toString());
}
靜態代理
首先先聲明一個主題
/** * 抽象主題:真實業務接口 */ public interface Subject { void doSome(); }
然后聲明一個真實的主題 生成真實主題的方法
//真實主題 private Subject subject=new RealSubject();
public class ProxySubject implements Subject { //真實主題 private Subject subject=new RealSubject(); @Override public void doSome() { //aop思想:增強 System.out.println("前置增強=========="); subject.doSome(); System.out.println("后置增強=========="); } }
5.使用多種方式實現AOP
Spring AOP實現原理:動態代理
5.1 JDK動態代理
JDK動態代理所用到的代理類在程序調用到代理類對象時才由JVM真正創建,JVM根據傳進來的 業務實現類對象 以及 方法名 ,動態地創建了一個代理類的class文件並被字節碼引擎執行,然后通過該代理類對象進行方法調用。
/** * 真實主題:將雨業務代碼封裝到這里 */ public class RealSubject implements Subject { @Override public void doSome() { System.out.println("==============真實業務============="); } }
2. 調用接口
public class ProxySubject implements Subject { //真實主題 private Subject subject=new RealSubject(); @Override public void doSome() { //aop思想:增強 System.out.println("前置增強=========="); subject.doSome(); System.out.println("后置增強=========="); } }
單步執行
@Test public void Spring(){ ProxySubject proxySubject = new ProxySubject(); proxySubject.doSome(); }
5.2 CGLIB動態代理
CGLIB是針對類來實現代理的,原理是對指定的業務類生成一個子類,並覆蓋其中業務方法實現代理。因為采用的是繼承,所以不能對final修飾的類進行代理。在JDK動態代理的基礎之上新建新的代理工廠Bean
/** * 業務類 */ public class IService { public void doSome(){ System.out.println("我是實現業務的方法"); } }
編寫測試類
public static void main(String[] args) { //CGLIB動態代理(當前項目必須有CGLIB的支持) //步驟一:目標對象 final IService iService=new IService(); //步驟二:通過CGLIB提供的Enhancer類生成代理 Enhancer enhancer=new Enhancer(); //步驟三:指定需要代理的目標對象模板(將目標對象放入到代理工廠當中,生成代理對象) enhancer.setSuperclass(iService.getClass()); //步驟四:實現增強的處理操作 enhancer.setCallback(new MethodInterceptor() { /** * * @param o 目標對象 * @param method 目標對象的方法 * @param objects 目標對象方法內的參數 * @param methodProxy 代理目標對象方法 * @return * @throws Throwable */ @Override public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable { System.out.println("前置"); Object invoke = methodProxy.invoke(iService, objects); System.out.println("后置"); return invoke; } }); //最后一步:創建代理 IService iServiceProxy = (IService)enhancer.create(); iServiceProxy.doSome();
6.Spring Bean的生命周期
6.1生命周期流程圖:
Spring Bean的完整生命周期從創建Spring容器開始,直到最終Spring容器銷毀Bean,這其中包含了一系列關鍵點。
若容器注冊了以上各種接口,程序那么將會按照以上的流程進行。下面將仔細講解各接口作用。
6.2各種接口方法分類
Bean的完整生命周期經歷了各種方法調用,這些方法可以划分為以下幾類:
1、Bean自身的方法:這個包括了Bean本身調用的方法和通過配置文件中<bean>的init-method和destroy-method指定的方法
2、Bean級生命周期接口方法:這個包括了BeanNameAware、BeanFactoryAware、InitializingBean和DiposableBean這些接口的方法
3、容器級生命周期接口方法:這個包括了InstantiationAwareBeanPostProcessor 和 BeanPostProcessor 這兩個接口實現,一般稱它們的實現類為“后處理器”。
4、工廠后處理器接口方法:這個包括了AspectJWeavingEnabler, ConfigurationClassPostProcessor, CustomAutowireConfigurer等等非常有用的工廠后處理器 接口的方法。工廠后處理器也是容器級的。在應用上下文裝配配置文件之后立即調用。
6.3演示
1、首先是一個簡單的Spring Bean,調用Bean自身的方法和Bean級生命周期接口方法,為了方便演示,它實現了BeanNameAware、BeanFactoryAware、InitializingBean和DiposableBean這4個接口,同時有2個方法,對應配置文件中<bean>的init-method和destroy-method。如下:
/** * @author qsk */ public class Person implements BeanFactoryAware, BeanNameAware, InitializingBean, DisposableBean { private String name; private String address; private int phone; private BeanFactory beanFactory; private String beanName; public Person() { System.out.println("【構造器】調用Person的構造器實例化"); } public String getName() { return name; } public void setName(String name) { System.out.println("【注入屬性】注入屬性name"); this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { System.out.println("【注入屬性】注入屬性address"); this.address = address; } public int getPhone() { return phone; } public void setPhone(int phone) { System.out.println("【注入屬性】注入屬性phone"); this.phone = phone; } @Override public String toString() { return "Person [address=" + address + ", name=" + name + ", phone="+ phone + "]"; } // 這是BeanFactoryAware接口方法 @Override public void setBeanFactory(BeanFactory arg0) throws BeansException { System.out.println("【BeanFactoryAware接口】調用BeanFactoryAware.setBeanFactory()"); this.beanFactory = arg0; } // 這是BeanNameAware接口方法 @Override public void setBeanName(String arg0) { System.out.println("【BeanNameAware接口】調用BeanNameAware.setBeanName()"); this.beanName = arg0; } // 這是InitializingBean接口方法 @Override public void afterPropertiesSet() throws Exception { System.out .println("【InitializingBean接口】調用InitializingBean.afterPropertiesSet()"); } // 這是DiposibleBean接口方法 @Override public void destroy() throws Exception { System.out.println("【DiposibleBean接口】調用DiposibleBean.destory()"); } // 通過<bean>的init-method屬性指定的初始化方法 public void myInit() { System.out.println("【init-method】調用<bean>的init-method屬性指定的初始化方法"); } // 通過<bean>的destroy-method屬性指定的初始化方法 public void myDestory() { System.out.println("【destroy-method】調用<bean>的destroy-method屬性指定的初始化方法"); } }
2、接下來是演示BeanPostProcessor接口的方法,如下:
package springBeanTest; import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.BeanPostProcessor; public class MyBeanPostProcessor implements BeanPostProcessor { public MyBeanPostProcessor() { super(); System.out.println("這是BeanPostProcessor實現類構造器!!"); // TODO Auto-generated constructor stub } @Override public Object postProcessAfterInitialization(Object arg0, String arg1) throws BeansException { System.out .println("BeanPostProcessor接口方法postProcessAfterInitialization對屬性進行更改!"); return arg0; } @Override public Object postProcessBeforeInitialization(Object arg0, String arg1) throws BeansException { System.out .println("BeanPostProcessor接口方法postProcessBeforeInitialization對屬性進行更改!"); return arg0; } }
如上,BeanPostProcessor接口包括2個方法postProcessAfterInitialization和postProcessBeforeInitialization,這兩個方法的第一個參數都是要處理的Bean對象,第二個參數都是Bean的name。返回值也都是要處理的Bean對象。這里要注意
3、InstantiationAwareBeanPostProcessor 接口本質是BeanPostProcessor的子接口,一般我們繼承Spring為其提供的適配器類InstantiationAwareBeanPostProcessor Adapter來使用它,如下:
package springBeanTest; import java.beans.PropertyDescriptor; import org.springframework.beans.BeansException; import org.springframework.beans.PropertyValues; import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessorAdapter; public class MyInstantiationAwareBeanPostProcessor extends InstantiationAwareBeanPostProcessorAdapter { public MyInstantiationAwareBeanPostProcessor() { super(); System.out .println("這是InstantiationAwareBeanPostProcessorAdapter實現類構造器!!"); } // 接口方法、實例化Bean之前調用 @Override public Object postProcessBeforeInstantiation(Class beanClass, String beanName) throws BeansException { System.out .println("InstantiationAwareBeanPostProcessor調用postProcessBeforeInstantiation方法"); return null; } // 接口方法、實例化Bean之后調用 @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { System.out .println("InstantiationAwareBeanPostProcessor調用postProcessAfterInitialization方法"); return bean; } // 接口方法、設置某個屬性時調用 @Override public PropertyValues postProcessPropertyValues(PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) throws BeansException { System.out .println("InstantiationAwareBeanPostProcessor調用postProcessPropertyValues方法"); return pvs; } }
這個有3個方法,其中第二個方法postProcessAfterInitialization就是重寫了BeanPostProcessor的方法。第三個方法postProcessPropertyValues用來操作屬性,返回值也應該是PropertyValues對象。
package springBeanTest; import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.config.BeanFactoryPostProcessor; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; public class MyBeanFactoryPostProcessor implements BeanFactoryPostProcessor { public MyBeanFactoryPostProcessor() { super(); System.out.println("這是BeanFactoryPostProcessor實現類構造器!!"); } @Override public void postProcessBeanFactory(ConfigurableListableBeanFactory arg0) throws BeansException { System.out .println("BeanFactoryPostProcessor調用postProcessBeanFactory方法"); BeanDefinition bd = arg0.getBeanDefinition("person"); bd.getPropertyValues().addPropertyValue("phone", "110"); } }
5、配置文件如下beans.xml,很簡單,使用ApplicationContext,處理器不用手動注冊:
<?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" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd"> <bean id="beanPostProcessor" class="springBeanTest.MyBeanPostProcessor"> </bean> <bean id="instantiationAwareBeanPostProcessor" class="springBeanTest.MyInstantiationAwareBeanPostProcessor"> </bean> <bean id="beanFactoryPostProcessor" class="springBeanTest.MyBeanFactoryPostProcessor"> </bean> <bean id="person" class="springBeanTest.Person" init-method="myInit" destroy-method="myDestory" scope="singleton" p:name="張三" p:address="廣州" p:phone="15900000000" /> </beans>
6、下面測試一下:
package springBeanTest; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class BeanLifeCycle { public static void main(String[] args) { System.out.println("現在開始初始化容器"); ApplicationContext factory = new ClassPathXmlApplicationContext("springBeanTest/beans.xml"); System.out.println("容器初始化成功"); //得到Preson,並使用 Person person = factory.getBean("person",Person.class); System.out.println(person); System.out.println("現在開始關閉容器!"); ((ClassPathXmlApplicationContext)factory).registerShutdownHook(); } }
關閉容器使用的是實際是AbstractApplicationContext的鈎子方法。
我們來看一下結果:
現在開始初始化容器 2014-5-18 15:46:20 org.springframework.context.support.AbstractApplicationContext prepareRefresh 信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@19a0c7c: startup date [Sun May 18 15:46:20 CST 2014]; root of context hierarchy 2014-5-18 15:46:20 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions 信息: Loading XML bean definitions from class path resource [springBeanTest/beans.xml] 這是BeanFactoryPostProcessor實現類構造器!! BeanFactoryPostProcessor調用postProcessBeanFactory方法 這是BeanPostProcessor實現類構造器!! 這是InstantiationAwareBeanPostProcessorAdapter實現類構造器!! 2014-5-18 15:46:20 org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons 信息: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@9934d4: defining beans [beanPostProcessor,instantiationAwareBeanPostProcessor,beanFactoryPostProcessor,person]; root of factory hierarchy InstantiationAwareBeanPostProcessor調用postProcessBeforeInstantiation方法 【構造器】調用Person的構造器實例化 InstantiationAwareBeanPostProcessor調用postProcessPropertyValues方法 【注入屬性】注入屬性address 【注入屬性】注入屬性name 【注入屬性】注入屬性phone 【BeanNameAware接口】調用BeanNameAware.setBeanName() 【BeanFactoryAware接口】調用BeanFactoryAware.setBeanFactory() BeanPostProcessor接口方法postProcessBeforeInitialization對屬性進行更改! 【InitializingBean接口】調用InitializingBean.afterPropertiesSet() 【init-method】調用<bean>的init-method屬性指定的初始化方法 BeanPostProcessor接口方法postProcessAfterInitialization對屬性進行更改! InstantiationAwareBeanPostProcessor調用postProcessAfterInitialization方法 容器初始化成功 Person [address=廣州, name=張三, phone=110] 現在開始關閉容器! 【DiposibleBean接口】調用DiposibleBean.destory()
@Test
public void Spring(){
ProxySubject proxySubject = new ProxySubject();
proxySubject.doSome();
}
后幾種動態代理
前置增強
首先需要主題對象
public interface IdomSomeService { void doSome(); }
/** * 原始對象 */ public class IdoSomeServiceImpl implements IdomSomeService { @Override public void doSome() { System.out.println("=========真實事物========="); } }
工廠代理類(實現了MethodBeforeAdvice):
public class MyBeforeAdvice implements MethodBeforeAdvice { @Override public void before(Method method, Object[] objects, Object o) throws Throwable { System.out.println("=============前置增強============="); } }
創建applicationContext.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:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <!--注入業務Bean--> <bean id="idomSomeService" class="cn.cglib.IdoSomeServiceImpl"></bean> <!--增強:切面--> <bean id="myBeforeAdvice" class="cn.cglib.MyBeforeAdvice"></bean> <!--使用代理工廠實現增強 --> <bean id="proxyFactory" class="org.springframework.aop.framework.ProxyFactoryBean"> <!--ProxyFactoryBean 將增強和業務織到一起--> <property name="target" ref="idomSomeService"></property> <!--攔截增強類--> <property name="interceptorNames" value="myBeforeAdvice"></property> <!--更換代理方式 proxyTargetClass默認值為false默認 是jdk動態代理, 但是當目標對象沒有接口時,自動改為cglib--> <property name="proxyTargetClass" value="true"></property> </bean> </beans>
實現類
public void cglib(){ ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); IdoSomeServiceImpl idoSomeService = (IdoSomeServiceImpl)ctx.getBean("proxyFactory"); idoSomeService.doSome(); }
環繞式增強
public interface IdomSomeService { void doSome(); }
/** * 原始對象 */ public class IdoSomeServiceImpl implements IdomSomeService { @Override public void doSome() { System.out.println("=========真實事物========="); } }
創建工廠類 實現了MethodInterceptor接口
public class MyBeforeAdvice implements MethodInterceptor { @Override public Object invoke(MethodInvocation invocation) throws Throwable { System.out.println("========環繞前========"); //調用核心業務方法 也可以獲取方法內的參數 也可以獲取目標對象 Object proceed = invocation.proceed(); Object aThis = invocation.getThis(); System.out.println(aThis); System.out.println("========環繞后========"); return proceed; } }
創建applicationContextHuan.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:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <!--注入業務Bean--> <bean id="idomSomeService" class="cn.cglib_huan.IdoSomeServiceImpl"></bean> <!--增強:切面--> <bean id="myBeforeAdvice" class="cn.cglib_huan.MyBeforeAdvice"></bean> <!--使用代理工廠實現增強 --> <bean id="proxyFactory" class="org.springframework.aop.framework.ProxyFactoryBean"> <!--ProxyFactoryBean 將增強和業務織到一起--> <property name="target" ref="idomSomeService"></property> <!--攔截增強類--> <property name="interceptorNames" value="myBeforeAdvice"></property> <!--更換代理方式 proxyTargetClass默認值為false默認 是jdk動態代理, 但是當目標對象沒有接口時,自動改為cglib--> <property name="proxyTargetClass" value="true"></property> </bean> </beans>
實現類與實現結果
@Test public void cglibHuan(){ ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContextHuan.xml"); IdoSomeServiceImpl idoSomeService = (IdoSomeServiceImpl)ctx.getBean("proxyFactory"); idoSomeService.doSome(); }
異常增強
public interface IdomSomeService { void doSome() throws Exception; }
/** * 原始對象 */ public class IdoSomeServiceImpl implements IdomSomeService { @Override public void doSome() throws Exception { int i =5/0; System.out.println("=========真實事物========="); } }
創建工廠類 實現ThrowsAdvice接口
public class MyBeforeAdvice implements ThrowsAdvice { public void afterThrowing(Exception ex){ System.out.println("發生異常"); } }
創建applicationContextExection.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:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <!--注入業務Bean--> <bean id="idomSomeService" class="cn.cglib_exception.IdoSomeServiceImpl"></bean> <!--增強:切面--> <bean id="myBeforeAdvice" class="cn.cglib_exception.MyBeforeAdvice"></bean> <!--使用代理工廠實現增強 --> <bean id="proxyFactory" class="org.springframework.aop.framework.ProxyFactoryBean"> <!--ProxyFactoryBean 將增強和業務織到一起--> <property name="target" ref="idomSomeService"></property> <!--攔截增強類--> <property name="interceptorNames" value="myBeforeAdvice"></property> <!--更換代理方式 proxyTargetClass默認值為false默認 是jdk動態代理, 但是當目標對象沒有接口時,自動改為cglib--> <property name="proxyTargetClass" value="true"></property> </bean> </beans>
相當於把異常拋出去,讓代碼繼續執行
執行類
@Test public void Text() { ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContextEx.xml"); IdoSomeServiceImpl proxyFactory = (IdoSomeServiceImpl)ctx.getBean("proxyFactory"); try { proxyFactory.doSome(); } catch (Exception e) { e.printStackTrace(); } System.out.println("23456123456"); }