Aop注解方式

Aop注解方式_第1张图片

package Calc;

import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;


public interface Calculator {
	public void add(int i,int j);
	public void sub(int i,int j);
	public void mul(int i,int j);
	public void div(int i,int j);
	
	public int add(int i,int j,int k);
}

package Calc;

import org.springframework.stereotype.Component;

@Component
public class CalculatorImp implements Calculator {

	public void add(int i, int j) {
		// TODO Auto-generated method stub
		int re=i+j;
		System.out.println(re);
	}

	public void sub(int i, int j) {
		// TODO Auto-generated method stub
		int re=i-j;
		System.out.println(re);
	}

	public void mul(int i, int j) {
		// TODO Auto-generated method stub
		int re=i*j;
		System.out.println(re);
	}

	public void div(int i, int j) {
		// TODO Auto-generated method stub
		int re=i/j;
		System.out.println(re);
	}

	public int add(int i, int j, int k) {
		// TODO Auto-generated method stub
		int re=i+j+k;
		
		return re;
	}

}







package Calc;

import java.lang.reflect.Array;
import java.util.Arrays;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

@Component
@Aspect
public class AopDemo {

	@Pointcut("execution(public void Calc.*.*(..))")
	public void express(){}
	@Before("express()")
	public void be(JoinPoint jp){
		System.out.println("前置通知:正在执行"+jp.getSignature().getName()+"方法,参数有"+Arrays.asList(jp.getArgs()));
	}
	
	@After("express()")
	public void af(JoinPoint jp){
		System.out.println("后置通知:"+jp.getSignature().getName()+"方法执行完了,谢谢!");
	}
	
	@AfterReturning(value="express()",returning="result")
	public void ar( Object result){
		result="asd";
		System.out.println("返回通知: "+result);
	}
	
	
	@AfterThrowing(value="express()",throwing="e")
	public void at(Exception e){
		System.out.println(e.getMessage());
	}
}

package Calc;

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

public class Main {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
		Calculator ci=ctx.getBean(Calculator.class);
//		ci.add(11, 22);
//		ci.sub(11, 22);
//		ci.mul(11, 22);
		Object num=ci.add(11, 22,33);
		System.out.println("num...."+num);
//		ci.div(11, 0);
		
	}

}

Aop注解方式_第2张图片

发烧不舒服,还是硬着头皮做好了作业,不知道后置通知和返回通知的区别在哪,网上也找不到案例,求答

你可能感兴趣的:(Java)