阿里雲大學JavaWeb開發系列課程:Spring框架入門第十五講使用註解實現aop

第三種實現方法—通過註解來實現

beans.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"
	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"/>
	<aop:aspectj-autoproxy/>
</beans>

log.java

package cn.sxt.log;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

@Aspect
public class Log {
	@Before("execution(* cn.sxt.service.impl.*.*(..))")
	public void before() {
		System.out.println("------方法執行前------");
	}
	@After("execution(* cn.sxt.service.impl.*.*(..))")
	public void after() {
		System.out.println("------方法執行後------");
	}
	@Around("execution(* cn.sxt.service.impl.*.*(..))")
	public Object around(ProceedingJoinPoint jp) throws Throwable {
		System.out.println("環繞前");
		System.out.println("簽名:"+jp.getSignature());
		//執行目標方法
		Object result=jp.proceed();
		System.out.println("環繞後");
		return result;
	}
	
}

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.delete();
	}
}

UserServiceImpl.java

package cn.sxt.service.impl;

import cn.sxt.service.UserService;

public class UserServiceImpl implements UserService{
	public void add() {
		System.out.println("------添加用戶數據------");
	}
	
	public int delete() {
		System.out.println("------刪除用戶數據------");
		return 1;
	}
}

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