//定义业务逻辑的抽象--Figure接口
package mypack;
public interface Figure {
void computeArea();
}
//定义业务逻辑的实现--圆形
package mypack;
public class Round implements Figure{
public void computeArea() {
System.out.println("计算圆形面积");
}
}
//定义业务逻辑的实现--正方形
package mypack;
public class Square implements Figure{
public void computeArea() {
System.out.println("计算正方形面积");
}
}
//对业务逻辑封装的抽象
package mypack;
public interface ComputeInterface {
public abstract void compute();
}
//对业务逻辑进行封装,并采用set注入方式来实现依赖注入
package mypack;
public class Compute implements ComputeInterface {
private Figure figure;
public Figure getFigure() {
return figure;
}
public void setFigure(Figure figure) { //set注入
this.figure = figure;
}
public void compute(){ //业务逻辑封装
figure.computeArea();
}
}
//将日志服务从业务逻辑中剥离出来产生一个Advice,这个Advice从而可以为其他业务逻辑反复使用
package mypack;
import java.lang.reflect.*;
import java.util.logging.*;
import org.springframework.aop.*;
public class LogBeforeAdvice implements MethodBeforeAdvice{
private Logger loger = Logger.getLogger(this.getClass().getName());
public void before(Method arg0, Object[] arg1, Object arg2) throws Throwable {
loger.log(Level.INFO, "方法开始启动 " + arg0);
}
}
//applicationContext.xml在后面做了很多事情,如实现依赖注入和产生动态代理对象将Advice织入到业务逻辑中
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id="round" class="mypack.Round">
</bean>
<bean id="square" class="mypack.Square">
</bean>
<bean id="compute" class="mypack.Compute">
<property name="figure">
<ref bean="round"/>
</property>
</bean>
<bean id="logBeforeAdvice" class="mypack.LogBeforeAdvice">
</bean>
<bean id="proxy" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="proxyInterfaces">
<value>mypack.ComputeInterface</value>
</property>
<property name="target">
<ref bean="compute"/>
</property>
<property name="interceptorNames">
<list>
<value>logBeforeAdvice</value>
</list>
</property>
</bean>
</beans>
//最后来写一段测试代码来测试上面的代码
package mypack;
import org.springframework.context.*;
import org.springframework.context.support.*;
public class TestDemo {
public static void main(String[] args) {
ApplicationContext context = new FileSystemXmlApplicationContext("applicationContext.xml");
ComputeInterface comp = (ComputeInterface)context.getBean("proxy");
comp.compute();
}
}