您的位置:首页 > 编程语言 > Java开发

面向切面编程:SpringAOP--注解的方式

2018-07-10 22:32 267 查看

研究spring这么久,就写写个人觉得比较有意思的东西----面向切面编程


切面类:

//定义切面
@Aspect
public class MyInterceptor {
     
//定义切入点,定义切入点及声明切入点
@Pointcut("execution(* com.sise.spring.service.impl.PersonServiceBean.add(..))")
private void add(){}

//定义前置通知
@Before("add()")
public void doBeforeMethod(){//方法名任意
System.out.println("add()方法的前置通知!");
}
//定义后置通知
@AfterReturning("add()")
public void doAfterReturning(){//方法名任意
System.out.println("add()方法的后置通知!");
}
//定义异常通知
@AfterThrowing("add()")
public void doAfterThrowing(){//方法名任意
System.out.println("add()方法的异常通知!");
}
//定义最终通知
@After("add()")
public void doAfter(){//方法名任意
System.out.println("add()方法的最终通知!");
}
//定义环绕通知
@Around("add()")
public Object add_doAround(ProceedingJoinPoint pjp)throws Throwable{//方法名任意
System.out.println("add()方法的环绕通知:进入方法");
Object result=pjp.proceed();//这个步骤作用是进入到你要切的那个方法中去执行它,执行完再出来
System.out.println("add()方法的环绕通知:退出方法");
return result;
}

}


服务类接口:

public interface PersonService {

       public void add(); //定义一个方法

}



服务类实现类:

public class PersonServiceBean implements PersonService{
@Override
public void add() {
System.out.println("执行add()!");
}

}



配置文件:

<?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 ">
   <aop:aspectj-autoproxy/>
   <bean id="myInterceptor" class="com.sise.spring.aop.MyInterceptor"  />  //切面类的bean
   <bean id="personService" class="com.sise.spring.service.impl.PersonServiceBean"  />//实现类的bean

</beans>



测试类:

public class SpringAopTest {

public static void main(String[] args) {
            ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
   PersonService personService=(PersonService) ctx.getBean("personService");
   personService.add();
   System.out.println(".........................");
}

}



输出的结果:

add()方法的环绕通知:进入方法
add()方法的前置通知!
执行add()!
add()方法的环绕通知:退出方法
add()方法的最终通知!
add()方法的后置通知!

.........................


从输出结果可以看出来,面向切面编程就是在执行你所想执行的业务之前,先去进行一些操作,然后执行完你的业务之后也可以 进行一系列的操作,用来做权限拦截会很适合

个人认为,注解配置是最简洁也是最易读懂的方式,第一篇,还有有点意思写得<Z>

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: