Sping之AOP
本篇學習aop的第一種實現(xiàn)方式使用spring API接口:MethodBeforeAdvice;AfterReturningAdvice
1、導入依賴,一定要導入正確!
<dependency><groupId>org.aspectj</groupId><artifactId>aspectjweaver</artifactId><version>1.9.4</version></dependency>2、創(chuàng)建接口
public interface UserService {void add();void delete();void update();void select(); }3、創(chuàng)建實現(xiàn)類,真實角色
public class UserServiceImpl implements UserService {@Overridepublic void add() {System.out.println("增加了一個用戶");}@Overridepublic void delete() {System.out.println("刪除了一個用戶");}@Overridepublic void update() {System.out.println("修改了一個用戶");}@Overridepublic void select() {System.out.println("查詢了一個用戶");} }4、創(chuàng)建要切入的前置和后置類
//前置 public class BeforeLog implements MethodBeforeAdvice {//method:要執(zhí)行的目標對象的方法//args:參數(shù)//target:目標對象@Overridepublic void before(Method method, Object[] args, Object target) throws Throwable {System.out.println(target.getClass().getName()+"的"+method.getName()+"被執(zhí)行");} }//后置 public class AfterLog implements AfterReturningAdvice {@Overridepublic void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {System.out.println("執(zhí)行"+method.getName()+"方法的結果為:"+returnValue);} }5、編寫applicationContext.xml配置文件:創(chuàng)建bean以及配置aop
?
<?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/beanshttps://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/aophttps://www.springframework.org/schema/aop/spring-aop.xsd"><!-- 配置bean--><bean id="userService" class="com.lizheng.service.UserServiceImpl"/><bean id="before" class="com.lizheng.log.BeforeLog"/><bean id="after" class="com.lizheng.log.AfterLog"/><!-- 配置aop--><aop:config><aop:pointcut id="pointcut" expression="execution(* com.lizheng.service.UserServiceImpl.*(..))"/><aop:advisor advice-ref="before" pointcut-ref="pointcut"/><aop:advisor advice-ref="after" pointcut-ref="pointcut"/></aop:config></beans>?6、測試類
public class MyTest {@Testpublic void myTset(){ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");UserService userService = context.getBean("userService", UserService.class);userService.delete();} }7、運行結果
?
?
?
?
?
總結
                            
                        - 上一篇: python类的使用
 - 下一篇: 淘宝、天猫商品详情最低价skuid爬取、