这是一篇使用aop思想实现对业务层功能的增强(加日志)的文章,网上关于aop的基础知识以及如何理解都非常多,这里不一一赘述。文章目的是作为本人学习记录、以及还暂时没有搞懂aop的各位,也许 就突然懂了
看完本片文章需要理解的几件事情:
1、对aop的理解
2、aop的基本概念以及各个通知方法的区别
3、文中各个地方的具体写法,为什么
4、通知方法的执行顺序
aop的具体使用详解
@Service
public class HelloService {
public void hello1() {
System.out.println("我是类的业务方法1");
}
public void hello2() {
System.out.println("我是类的业务方法2");
}
public void hello3() {
System.out.println("我是类的业务方法3");
}
}
@Aspect
@Component
public class HelloAspect {
@Pointcut(value = "execution(* com.newtouc.energy.business.aop.HelloService.*(..))")
public void pointCut() {
// Do nothing
}
@Before("pointCut()")
public void beforeService() {
System.out.println("日志开始了");
}
@After("pointCut()")
public void afterService() {
System.out.println("日志结束了");
}
@Around("pointCut()")
public void aroundService(ProceedingJoinPoint pjp) {
System.out.println("日志开始时间----------" + new Date());
try {
pjp.proceed(); //执行业务方法
} catch (Throwable e) {
e.printStackTrace();
}
System.out.println("日志结束时间----------" + new Date());
}
}
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBootApplicationTests {
@Autowired
private HelloService helloService;
@Test
public void contextLoads() {
//设置用户名
// CurrentUserHolder.set("hello");
helloService.hello1();
helloService.hello2();
helloService.hello3();
}
}
执行结果(如图):