SpringBoot学习_SpringAOP的那些事儿

1.创建一个简单的SpringBoot应用,然后在pom文件中引入spring-boot-start-aop.

    <dependency>

        <groupId>org.springframework.boot</groupId>

        <artifactId>spring-boot-starter-aop</artifactId>

    </dependency>

2.编写一个AOP切面类:

package com.jinyu.springboot.config;

import java.util.Arrays;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.context.annotation.Configuration;

@Configuration
@Aspect
public class AOPConfig {
	@Around("@within(org.springframework.stereotype.Controller)")
	public Object simpleAop(final ProceedingJoinPoint pjp) {
		
		Object[] args = pjp.getArgs();
		System.out.println("args:"+Arrays.asList(args));
		//调用原有的方法
        Object o = null;
		try {
		    o = pjp.proceed();
			System.out.println("return:"+o);
			
		} catch (Throwable e) {
			e.printStackTrace();
		}
		return o;
		
	}

}
package com.jinyu.springboot.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class HelloWorldController {
    @RequestMapping("/hello.do")
	public @ResponseBody String say(String name) {
		return "Hello Spring Boot";
	}
}

输入http://localhost:8080/hello.do?name=aaa的时候,查看控制台,会发现有如下输出:

b1e8b20090c840771b29a77a2325a8d9c6a.jpg

SpringAOP支持多种表达式及表达式的组合,例如:

execution(public **(..)):所有public方法,后面的星号代表类路径和方法名。

execution(* set*(..)):所有set开头的方法。

execution(public set*(..)):所有set开头的public方法。

execution(public com.xyz.service.* set*(..)):所有set开头的public方法,且位于com.xyz.service包下。

target(com.xyz.service.CommonService):所有实现了CommonService借口的类的方法。

@target(org.springframework.transaction.annotation.Transactional):所有用@Transactional注解的方法。

@within(org.springframework.stereotype.Controller):类型声明了@Controller注解的所有方法。

转载于:https://my.oschina.net/pengbina/blog/2874741

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值