BookService类
package com.hkd.service;public interface BookService {public void buyJava();public int comment();void buy(); }
BookServiceImp类
package com.hkd.service;import org.springframework.stereotype.Component;@Component("bs") public class BookServiceImp implements BookService{@Overridepublic void buyJava() {System.out.println("买Java书");}@Overridepublic int comment() {System.out.println("========书评");return 1;}@Overridepublic void buy() {System.out.println("=======买书");} }
MyAdvice类
package com.hkd.tzhs;import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; import org.springframework.stereotype.Component; import org.aspectj.lang.ProceedingJoinPoint; @Aspect @Component public class MyAdvice {@Pointcut("execution(* com.hkd.service.BookServiceImp.*(..))")public void mypointCut(){}@Pointcut("mypointCut()")public void mybefore(){System.out.println("前置");}@Pointcut("mypointCut()")public void myafter(){System.out.println("出现异常执行的后置");}@Pointcut("mypointCut()")public void myaftering(){System.out.println("出现异常不执行的后置");}@Pointcut("mypointCut()")public Object myarround(ProceedingJoinPoint p) throws Throwable {System.out.println("执行环绕");System.out.println("环绕前置");Object obj=p.proceed();System.out.println("环绕后置");return obj;}}
spring.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:aop="http://www.springframework.org/schema/aop"xmlns:context="http://www.springframework.org/schema/context"xmlns:mvc="http://www.springframework.org/schema/mvc"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd"> <context:component-scan base-package="com.hkd.service"/><context:component-scan base-package="com.hkd.tzhs"/><aop:aspectj-autoproxy/> </beans>
测试类
import com.hkd.service.BookService; import org.springframework.beans.factory.BeanFactory; import org.springframework.context.support.ClassPathXmlApplicationContext;public class Test {@org.junit.Testpublic void testAspect(){BeanFactory beanFactory=new ClassPathXmlApplicationContext("spring.xml");BookService bookService= (BookService) beanFactory.getBean("bs");bookService.buyJava();bookService.buy();bookService.comment();} }
目录