- Service接口:
- public interface PersonService {
- public void save(String name);
- public void update(String name, Integer id);
- public String getName(Integer id);
- }
- 接口实现:
- public class PersonServiceimp implements PersonService{
- @Override
- public void save(String name) {
- System.out.println("woshi save()");
- }
- @Override
- public void update(String name, Integer id) {
- System.out.println("woshi update()");
- }
- @Override
- public String getName(Integer id) {
- System.out.println("woshi getName()");
- return id+"";
- }
- }
- 切面类:
- @Aspect
- public class Myintercepter {
- @Pointcut("execution (* snail.serviceimp.PersonServiceimp.*(..))")
- public void anyMethod(){}
- @Before("anyMethod() && args(userName)")//定义前置通知,anyMethod()是必须的方法,//args(username)不是必须的,是接收方法的参数
- public void doAccessCheck(String userName) {
- System.out.println("前置通知"+userName);
- }
- @AfterReturning(pointcut="anyMethod()",returning="revalue")//定义后置通知 returning参数是接收被拦截的方法的返回值
- public void doReturnCheck(String revalue) {
- System.out.println("后置通知"+revalue);
- }
- @AfterThrowing(pointcut="anyMethod()", throwing="ex")//定义例外通知
- public void doExceptionAction(Exception ex) {
- System.out.println("例外通知"+ex);
- }
- @After("anyMethod()")//定义最终通知
- public void doReleaseAction() {
- System.out.println("最终通知");
- }
- @Around("anyMethod()")//环绕通知
- public Object doBasicProfiling(ProceedingJoinPoint pjp) throws Throwable {
- System.out.println("环绕通知");
- return pjp.proceed();
- }
- }
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:context="http://www.springframework.org/schema/context"
- xmlns:aop="http://www.springframework.org/schema/aop"
- xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context-3.0.xsd
- http://www.springframework.org/schema/aop
- http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
- ">
- <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
- <bean id="aop" class="snail.service.Myintercepter"></bean>
- <bean id="pp" class="snail.serviceimp.PersonServiceimp"></bean>
- </beans>
测试类:
- public class test {
- public static void main(String[] args) {
- ApplicationContextatx=new ClassPathXmlApplicationContext("applicationContext.xml");
- PersonService b=(PersonService) atx.getBean("pp");
- //Myintercepter ss=(Myintercepter)atx.getBean("aop");
- b.save("保存snail");
- b.getName(1);
- b.update("gengxin", 5);
- }
- }