阿里雲大學JavaWeb開發系列課程:Spring框架入門第十二講使用spring aopApi實現(補)

5、使用spring實現aop

第一種方式—通過springAPI來實現aop

Log.java--前置通知

package cn.sxt.log;

import java.lang.reflect.Method;

import org.springframework.aop.MethodBeforeAdvice;

public class Log implements MethodBeforeAdvice{
	/*
	 * @param method 被調用方法對象
	 * @param args 被調用的方法的參數
	 * @param target 被調用方法的目標對象
	 */ 
	@Override
	public void before(Method method, Object[] args, Object target) 
			throws Throwable {
		System.out.println(target.getClass().getName()+"的"+method.getName()+"方法被執行");	
	}
}

AfterLog.java

package cn.sxt.log;

import java.lang.reflect.Method;

import org.springframework.aop.AfterReturningAdvice;

public class AfterLog implements AfterReturningAdvice{
	/*目標方法執行的通知
	 * returnValue--返回值
	 * method 被調用的方法對象
	 * args 被調用的方法對象的目標對象
	 * target 被調用的方法對象的目標對象
	 */
	@Override
	public void afterReturning(Object returnValue, Method method, Object[] args, Object target) 
			throws Throwable {
		// TODO 自動生成的方法存根
		System.out.println(target.getClass().getName()+"的"+method.getName()+"被執行,返回值是:"+returnValue);
	}
	
}

目標類UserServiceImpl.java

package cn.sxt.service;

public class UserServiceImpl implements UserService{
	public void add(int a) {
		System.out.println("增加用戶");
	}
	public void update() {
		System.out.println("修改用戶");
	}
	public void delete() {
		System.out.println("刪除用戶");
	}
	public void search() {
		System.out.println("查詢用戶");
	}

}

spring的配置文件

<?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">
	<bean id="userService" class="cn.sxt.service.impl.UserServiceImpl"></bean>
	<bean id="log" class="cn.sxt.log.Log"/>
	<bean id="afterLog" class="cn.sxt.log.AfterLog"/>
	<aop:config>
		<aop:pointcut expression="execution(* cn.sxt.service.impl.*.*(..))" id="pointcut"/>
		<aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
		<aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
	</aop:config>
</beans>

Test.java

package cn.sxt.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import cn.sxt.service.UserService;



public class Test {
	public static void main(String[] args) {
		ApplicationContext ac=new ClassPathXmlApplicationContext("beans.xml");
		UserService userService =(UserService)ac.getBean("userService");
		userService.add(2);
	}
}

UserService.java

package cn.sxt.service;

public interface UserService {
	public void add(int a);
	public void update();
	public void delete();
	public void search();
	
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章