AOP(Aspect Oriented Programming)面向切面编程
通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术
项目结构:
1.首先定义一个接口:
IDeviceWriter.java
package beans.po;
public interface IDeviceWriter {
public void save(int a,String b);
}
2.实现接口的两种方式:
package beans.po;
public class HDWriter implements IDeviceWriter {
public void save(int a,String b) {
System.out.println("hello I'm HD Writer");
}
}
package beans.po;
public class USBWriter implements IDeviceWriter{
public void save(int a,String b) {
System.out.println("hello I'm USB Writer");
}
}
3. AOP代理
package beans.business;
import beans.po.IDeviceWriter;
public class BusinessBean {
private IDeviceWriter writer;
public void setDeviceWriter(IDeviceWriter writer) {
this.writer = writer;
}
public IDeviceWriter getDeviceWriter() {
return writer;
}
public void savedata(int a,String b) {
if (writer == null) {
throw new RuntimeException("DeviceWriter needed...");
}
writer.save(a,b);
}
}
4.切口函数
package beans.advice;
import org.aspectj.lang.JoinPoint;
public class InjectionAdvice {
public void before(JoinPoint jp){
if(jp==null){
System.out.println("jp为空");
}
System.out.println("类名"+jp.getTarget().getClass().getName());
System.out.println("调用的方法"+jp.getSignature().getName());
Object[] arys=jp.getArgs();
for(int i=0;i<arys.length;i++){
System.out.print(arys[i]+"--");
}
System.out.println("参数");
System.out.println("before was waved and called");
}
public void after(){
System.out.println("after was waved and returned");
}
}
5.applicationConetxt.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"
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.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<bean id="hd" class="beans.po.HDWriter"/>
<bean id="usb" class="beans.po.USBWriter"/>
<bean id="businessBean" class="beans.business.BusinessBean">
<property name="deviceWriter">
<ref bean="hd"/>
</property>
</bean>
<bean id="injectionAdvice" class="beans.advice.InjectionAdvice"/>
<aop:config>
<aop:aspect id="test" ref="injectionAdvice">
<aop:pointcut id="savecut" expression="execution (* beans.po.*.*(..))"/>
<aop:before pointcut-ref="savecut" method="before"/>
<aop:after pointcut-ref="savecut" method="after"/>
</aop:aspect>
</aop:config>
</beans>