注解式 Spring AOP初识

Why AOP?
  1. 减少代码
  2. 就是为了更清晰的逻辑,可以让你的业务逻辑去关注自己本身的业务,而不去想一些其他的事情。这些其他的事情包括:安全、事务、日志等。 


demo工程如下:

1.定义一个Service基础类。

@Service("math")
public class Math {
	public int add(int n1,int n2){
		int result = n1 + n2;
		System.out.println("result = "+ n1 + "+"+ n2);
		return result;
	}
	
	
	public int sub(int n1 ,int n2){
		int result = n1 -n2;
		System.out.println("result = "+n1 +"-" + n2);
		return result;
	}
	
	 public int mul(int n1,int n2){
	        int result=n1 * n2;
	        System.out.println(n1+"X"+n2+"="+result);
	        return result;
	    }
	    
	   
	    public int div(int n1,int n2){
	        int result=n1/n2;
	        System.out.println(n1+"/"+n2+"="+result);
	        return result;
	    }
}
使用@Service注解标注该类是Service业务类

2. 定义Advice类,通知类。在该类中定义你想要的功能。 也就是上说的安全、事物、日志等。你给先定义好,然后再想用的地方用一下。包含Aspect的一段处理代码

@Component
@Aspect
public class Advices {
	@Before("execution(* com.imut.Math.*(..))")
	public void before1(JoinPoint jp){
		System.out.println("-----先-----");
		System.out.println(jp.getSignature().getName());
	}
	@After("execution(* com.imut.Math.*(..))")
	public void after(JoinPoint jp){
		System.out.println("-----后-----");
		System.out.println("");
	}
}
使用@Component注解表名当前是一个组件,@Aspect表名当前是一个切面,

3.定义.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:p="http://www.springframework.org/schema/p"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    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-4.3.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.3.xsd">
	
	<context:component-scan base-package="com.imut"></context:component-scan>  <!-- 扫面整个包 -->
	
	<aop:aspectj-autoproxy proxy-target-class="true"></aop:aspectj-autoproxy> 

</beans>

4.定义Test

public class Test {

	public static void main(String[] args){
		ApplicationContext ac = new ClassPathXmlApplicationContext("aop01.xml");
		Math math = ac.getBean("math", Math.class);
		 int n1 = 30, n2 = 5;
	        math.add(n1, n2);
	        math.sub(n1, n2);
	        math.mul(n1, n2);
	        math.div(n1, n2);
		System.out.println("ddd");
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值