目录
1、pom文件,需要添加web和aop的boot依赖。
<!-- 如果是web应用,需要引入的web相关依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 添加boot的aop相关依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
2、定义controller和service。
package xyz.jangle.springboot.demo.ctrl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import xyz.jangle.springboot.demo.service.AService;
@RestController
@RequestMapping("/testCtrl")
public class TestCtrl {
@Autowired
private AService aService;
@RequestMapping("/hello.ctrl")
public String hello() {
System.out.println("just so so ...");
aService.testMethod("这是方法的输出");
return "hello";
}
public static void main(String[] args) {
}
}
service:
package xyz.jangle.springboot.demo.service;
/**
* @author jangle
* @email jangle@jangle.xyz
* @time 2021年2月8日 下午4:48:37
*
*/
public interface AService {
void testMethod(String str);
}
package xyz.jangle.springboot.demo.service.impl;
import org.springframework.stereotype.Service;
import xyz.jangle.springboot.demo.service.AService;
/**
* @author jangle
* @email jangle@jangle.xyz
* @time 2021年2月8日 下午4:49:06
*
*/
@Service
public class AServiceImpl implements AService {
@Override
public void testMethod(String str) {
System.out.println(str);
}
}
3、编写切面类
package xyz.jangle.springboot.demo.aop;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
/**
*
* 方面编程
* @author jangle
* @email jangle@jangle.xyz
* @time 2021年2月8日 上午11:39:01
*
*/
// 1、这个类称之为切面
@Aspect
@Component
public class MyAopDemo {
// 2、此处定义切入点(接入点的集合)
@Pointcut("execution (public * xyz.jangle.springboot.demo.service..*(..))")
public void servicePointcut() {
}
// 3、此处定义通知
@Around("servicePointcut()")
public Object around(ProceedingJoinPoint joinPoint) {
Object proceed = null;
try {
proceed = joinPoint.proceed();
System.out.println("around after 1111");
} catch (Throwable e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return proceed;
}
}
4、运行boot项目
访问:http://127.0.0.1/testCtrl/hello.ctrl
程序输出结果:
just so so ...
这是方法的输出
around after 1111

本文详细介绍了如何在Spring Boot项目中配置并使用AOP,包括添加web和aop依赖,定义Controller和服务,编写切面类,以及运行项目后的输出结果展示。通过一个具体的例子展示了AOP在方法调用前后的增强操作。
2692

被折叠的 条评论
为什么被折叠?



