在没有 xml 的情况下,Spring 的 运行 方面如何?
How run aspect in Spring without xml?
如何 运行 Java 中的一个方面。
如何 运行 Spring 中的一个方面使用注释,没有 xml 文件?
许多其他教程使用 xml 文件进行配置。
在您的 class 上使用注释:
@零件
@看点
定义自定义注释;
@Target({ElementType.TYPE ,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface Loggable {
}
注释您要拦截的方法;
@Service
public class MyAwesomeService {
@Loggable
public void myAwesomemethod(String someParam) throws Exception {
// do some awesome things.
}
}
将方面依赖项添加到您的 pom。
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
</dependency>
并定义你的方面 class ;
@Aspect
@Component
public class LoggingHandler {
@Before("@annotation(com.example.annotation.Loggable)")
public void beforeLogging(JoinPoint joinPoint){
System.out.println("Before running loggingAdvice on method=");
}
@After("@annotation(com.example.annotation.Loggable)")
public void afterLogging(JoinPoint joinPoint){
System.out.println("After running loggingAdvice on method=");
}
}
如何 运行 Java 中的一个方面。
如何 运行 Spring 中的一个方面使用注释,没有 xml 文件?
许多其他教程使用 xml 文件进行配置。
在您的 class 上使用注释: @零件 @看点
定义自定义注释;
@Target({ElementType.TYPE ,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface Loggable {
}
注释您要拦截的方法;
@Service
public class MyAwesomeService {
@Loggable
public void myAwesomemethod(String someParam) throws Exception {
// do some awesome things.
}
}
将方面依赖项添加到您的 pom。
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
</dependency>
并定义你的方面 class ;
@Aspect
@Component
public class LoggingHandler {
@Before("@annotation(com.example.annotation.Loggable)")
public void beforeLogging(JoinPoint joinPoint){
System.out.println("Before running loggingAdvice on method=");
}
@After("@annotation(com.example.annotation.Loggable)")
public void afterLogging(JoinPoint joinPoint){
System.out.println("After running loggingAdvice on method=");
}
}