1. aop实现方式
- 继承spring原生的aop的类,前置、后置、环绕
- xml配置
- 注解的使用
- 自定义注解
2. 自定义注解学习
package com.tom.tom.aspect.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MyLog {
String value() default "default";
}
package com.tom.tom.aspect.aop;
import com.tom.tom.aspect.annotation.MyLog;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
@Component
@Aspect
public class LogAspect {
@Around("@annotation(annotation)")
public Object aopMethod(final ProceedingJoinPoint joinPoint, final MyLog annotation) throws Throwable {
MyLog log = ((MethodSignature) joinPoint.getSignature()).getMethod().getAnnotation(MyLog.class);
System.out.println("before " + log.value());
Object proceed = joinPoint.proceed();
System.out.println("after" + log.value());
return proceed;
}
}
package com.tom.tom.service;
public interface IMyService {
public int getServiceId(String name);
public String getServiceName(int id);
}
package com.tom.tom.service.impl;
import com.tom.tom.aspect.annotation.MyLog;
import com.tom.tom.service.IMyService;
import org.springframework.stereotype.Service;
@Service("myService")
public class MyServiceImpl implements IMyService {
@Override
public int getServiceId(String name) {
return 0;
}
@Override
@MyLog("hahhhaa")
public String getServiceName(int id) {
System.out.println(id);
return null;
}
}
package com.tom.tom;
import com.tom.tom.service.IMyService;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
@SpringBootApplication
public class TomApplication {
public static void main(String[] args) {
ConfigurableApplicationContext run = SpringApplication.run(TomApplication.class, args);
IMyService myService = run.getBean("myService", IMyService.class);
System.out.println(myService.getServiceName(90));
}
}
目录
➜ tom tree .
.
├── pom.xml
├── src
│ ├── main
│ │ ├── java
│ │ │ └── com
│ │ │ └── tom
│ │ │ └── tom
│ │ │ ├── TomApplication.java
│ │ │ ├── aspect
│ │ │ │ ├── annotation
│ │ │ │ │ └── MyLog.java
│ │ │ │ └── aop
│ │ │ │ └── LogAspect.java
│ │ │ └── service
│ │ │ ├── IMyService.java
│ │ │ └── impl
│ │ │ └── MyServiceImpl.java
│ │ └── resources
│ │ └── application.properties
│ └── test
│ └── java
│ └── com
│ └── tom
│ └── tom
│ └── TomApplicationTests.java
└── tom.iml
结果
before hahhhaa
90
afterhahhhaa
null