- 概念与分类
概念: 切面+通知
前置通知(常用于权限,缓存,开启事务,日志,以@Start)
环绕通知(使用@Around),后置通知(使用@After),返回后通知,异常通知
以@Aspect+@Component,注解切面类 - 定义切点
在方法上加注解@Pointcut
切点表达式:*
表示1个 …表示多个*
依次代表方法返回值,类名,方法名,(…)是参数列表@Pointcut("execution(* cn.tedu.service.*.*(..))")
- 案例
@Component
@Aspect
public class TimerUse {
@Pointcut("execution(* cn.tedu.controller.*.*(..))")
public void cutpoint(){}
@Before("cutpoint()")
public void before(JoinPoint joinPoint){
System.out.println("前置通知");
}
@After("cutpoint()")
public void After(JoinPoint joinPoint){
System.out.println("后置通知");
}
@Around("cutpoint()")
public Object Around(ProceedingJoinPoint joinPoint) throws Throwable {
Long time = System.currentTimeMillis();
Object o = joinPoint.proceed();//aop自动执行方法
time = System.currentTimeMillis()-time;//耗时
System.out.println(time);
return o;//返回给调用者,继续执行方法
}
}
Spring整合SpringMVC框架
在接口中,JDK1.8也可以有static或者default普通方法
@RestController
@RequestMapping("car")
public class CarController {
@Autowired
private CarService carService;
@RequestMapping("get")
public List<Car> get(Car c){
return carService.get();
}
}
public interface CarService {
List<Car> get();
}
@Service
public class CarServiceImpl implements CarService{
@Override
public List<Car> get() {
List<Car> l = new ArrayList<>();
Car c1 =new Car();
c1.setName("Proche");
c1.setColor("White");
c1.setPrice(88.88);
Car c2 =new Car();
c2.setName("Audi");
c2.setColor("Gray");
c2.setPrice(66.66);
l.add(c1);
l.add(c2);
return l;
}
}
server:
port: 8000
前端页面(AJAX)
注意在CarController加上注解@CrossOrigin,以让后端服务器放行
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="../js/vue.js"></script>
<script src="../js/axios.min.js"></script>
</head>
<body>
<div id="app">
<button @click="flash()">点我刷新</button>
</div>
<script>
new Vue({
el:"#app",
methods:{
flash(){
axios.get("http://localhost:8000/car/get").then(
//把服务器的返回值交给a保存
a => {console.log(a.data)}
)
}
}
})
</script>
</body>
</html>