使用@Aspect注解开发Spring Aop
首先我们先在spring.xml里加入启动aop的代码:
<?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:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.2.xsd">
<!-- 扫描 -->
<context:component-scan base-package="com.hanlin.*"/>
<!--启动aop-->
<aop:aspectj-autoproxy/>
</beans>
注意其中的<aop:aspectj-autoproxy/>是启动aop的关键代码
action的代码
package com.hanlin.action;
import com.hanlin.server.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @author:hanlin.yuan
* @date:2019/3/4
*/
@Controller
public class TestAction {
@Autowired
private UserService userService;
@RequestMapping("/test.do")
public String info(HttpServletRequest request, HttpServletResponse response){
userService.test();
return "index";
}
}
注释:代码非常简单,就是调用test.do来访问userservice.test方法
userservice代码
package com.hanlin.server;
/**
* @author:hanlin.yuan
* @date:2019/3/4
*/
public interface UserService {
void test();
}
userserviceImpl代码
package com.hanlin.server.impl;
import com.hanlin.server.UserService;
import org.springframework.stereotype.Service;
/**
* @author:hanlin.yuan
* @date:2019/3/4 0004
*/
@Service
public class UserServiceImpl implements UserService {
@Override
public void test() {
System.out.println("测试");
}
}
UserAspect代码
package com.hanlin.aspect;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
/**
* aop通知注解
* @author:hanlin.yuan
* @date:2019/3/12
*/
@Aspect
@Component
public class UserAspect {
/**
* @Pointcut 定义一个切点,避免重复引用
*/
@Pointcut("execution(* com.hanlin.server.impl.UserServiceImpl.test(..))")
public void print(){}
@Before("print()")
public void before(){
System.out.println("我是前置通知");
}
@After("print()")
public void After(){
System.out.println("我是后置通知");
}
@AfterReturning("print()")
public void AfterReturning(){
System.out.println("我是返回通知");
}
@AfterThrowing("print()")
public void AfterThrowing(){
System.out.println("我是异常通知");
}
}
最后我们调用test.do就会发现,控制台打印如下:
显然切面的通知已经通过aop植入到了约定的流程当中了,这时我们就可以用aop来处理一些需要切面的场景了