标签:
Spring 的 aop操作:
aop 相当于以前的过滤器,有拦截的功能
这里举个客人购买空调的例子。
在用户购买之前,输出欢迎信息,在购买之后输出购买的空调信息;若果没有了这个商品,则跳转自定义错误。
1.定义购买之前的before方法;FrigBefore()
public class FrigBefore {
public void before(JoinPoint jp) throws Throwable{
String com=(String)jp.getArgs()[0];//获取在FrigBizImp里面定义的方法的第一个参数,客户的名称
System.out.println("欢迎光临"+com);
}
}
2.定义商品不存在的错误NoThisFrig()
public class NoThisFrig extends Exception{
private static final long serialVersionUID = 3259019719837934771L;
public NoThisFrig(String msg){
super(msg);
}
}
3.定义购买方法并抛出自定义异常NoThisFrig
public void buyFrig(String frig, String customer) throws NoThisFrig {
if("美的".equals(frig)){
throw new NoThisFrig("对不起没有"+frig+"的货了");
}
System.out.println("您已经成功购买一台"+frig);
}
4.定义测试方法
public class test {
public static void main(String[] args) throws NoThisFrig {
ApplicationContext app =
new ClassPathXmlApplicationContext("applicationContext.xml");
FrigBiz f=(FrigBiz) app.getBean("frigBizImp");
f.buyFrig("美的","李敏");
}
}
5.在applicationContext.xml页面里面配置文件
<bean id="frigBizImp" class="com.zzzy.DaoImp.FrigBizImp"/>
<bean id="frigBefore" class="com.zzzy.AOP.FrigBefore"/>
<aop:config>
<aop:pointcut id="p1" expression="execution(void buyFrig(String,String))"/>
<aop:aspect id="logAspect" ref="frigBefore">
<aop:before method="before" pointcut-ref="p1"/>
</aop:aspect>
</aop:config>
<!-- 打印机 的配置 -->
<bean id="color" class="com.zzzy.Entity.ColorInk"/>
<bean id="gark" class="com.zzzy.Entity.GrayInk"/>
<bean id="a3" class="com.zzzy.Entity.A3Page"/>
<bean id="a4" class="com.zzzy.Entity.A4Page"/>
<bean id="pointBefore" class="com.zzzy.AOP.PrintBefore"/>
<bean id="printer" class="com.zzzy.DaoImp.Printer">
<property name="ink" ref="color"/>
<property name="page" ref="a3"/>
</bean>
<aop:config>
<aop:pointcut id="p2" expression="execution(void printInfo())"/>
<aop:aspect id="printAspect" ref="pointBefore">//这里一定要是pointBefore 而不是pointer
//切面里面的ref--是before的类
<aop:before method="before" pointcut-ref="p2"/>
</aop:aspect>
</aop:config>
//使用注解方式配置切面
1.启用注解配置 <aop:aspect-autoproxy/>
2.配置目标业务对象
<bean id="a" class="com.zzzy.DaoImp"></bean>
3.配置切面
<bean class="com.zzzy.LogAspect"></bean>
4.用注解配置切面的
@Aspect
public class FrigAspect {
//配置异常通知
@AfterThrowing(pointcut="execution(void buyFrig(String,String))",throwing="e")
public void afterThrowing(NoThisFrig e)throws Throwable{
System.out.println("通知仓库,赶紧订货!");
}
}
5.在业务方法的类中注解配置
@Repository
public class FrigBizImp implements FrigBiz{
public void buyFrig(String frig, String customer) throws NoThisFrig {
if("美的".equals(frig)){
throw new NoThisFrig("对不起没有"+frig+"的货了");
}
System.out.println("您已经成功购买一台"+frig);
}
}
标签:
原文地址:http://www.cnblogs.com/wjn563/p/4245154.html