面向切面AOP编程---Spring框架介绍(二)
?????? <aop:aspectj-autoproxy />??????????????? //? 启动对@Aspect注解进行支持
</beans>
Spring?提供两种切面使用方式(分别是基于XML配置方式和基于注解方式),这里我们采用注解的方式。
第二步,创建业务层业务Bean接口及实现类,代码如下:
接口:
package com.lyk.service;
public interface PersonService {
?public void save(String name);
?public void update(String name, Integer id);
?public String getPersonName(Integer id);
}
实现类:
package com.lyk.service.impl;
import cn.lyk.service.PersonService;
public class PersonServiceBean implements PersonService {
?public String getPersonName(Integer id) {
??System.out.println("我是getPersonName()方法");
??return "xxx";
?}
?public void save(String name) {
??throw new RuntimeException("我爱例外");
??//System.out.println("我是save()方法");
?}
?public void update(String name, Integer id) {
??System.out.println("我是update()方法");
?}
}
至此准备工作做好,第三步正式进行AOP开发。编写一个被声明为切面的类(其中要定义切入点、定义环绕通知等)。代码如下:
package com.lyk.service;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
/**
?* 切面
?*
?*/
@Aspect
public class MyInterceptor {
?@Pointcut("execution (* com.lyk.service.impl.PersonServiceBean.*(..))")
?private void anyMethod() {}//声明一个切入点
?
?@Before("anyMethod() && args(name)")
?public void doAccessCheck(String name) {
??System.out.println("前置通知:"+ name);
?}
?@AfterReturning(pointcut="anyMethod()",returning="result")
?public void doAfterReturning(String result) {
??System.out.println("后置通知:"+ result);
?}
?@After("anyMethod()")
?public void doAfter() {
??System.out.println("最终通知");
?}
?@AfterThrowing(pointcut="anyMethod()",throwing="e")
?public void doAfterThrowing(Exception e) {
??System.out.println("例外通知:"+ e);
?}
?
?@Around("anyMethod()")
?public Object doBasicProfiling(ProceedingJoinPoint pjp) throws Throwable {
??//if(){//判断用户是否在权限
??System.out.println("进入方法");
??Object result = pjp.proceed();
??System.out.println("退出方法");
??//}
??return result;
?}
?
}
此外,还要将定义的业务Bean和切面类交给Spring管理,添加相应的配置文件。如下:
??????? <bean id="myInterceptor" class="com.lyk.service.impl.PersonServiceBean"></bean>
第四步,进行Juit测试。代码如下:
package junit.test;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.lyk.service.PersonService;
public class SpringAOPTest {
?@BeforeClass
?public static void setUpBeforeClass() throws Exception {
?}
?@Test public void interceptorTest(){
??ApplicationContext cxt = new ClassPathXmlApplicationContext("beans.xml");
??PersonService personService = (PersonService)cxt.getBean("personService");
??personService.save("xx");
?}
}
如能顺利通过测试,则可看到Junit测试出现绿条,且控制台有正确的结果显示。
over~
?