在Spring Boot Application中,不执行基于注释的切入点

时间:2016-04-24 23:34:19

标签: java spring spring-boot spring-aop

您好我已经创建了Spring启动应用程序并尝试使用spring AOP应用Aspect。代码如下......

自定义Timer注释

package org.my.pckg.annotation;

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface Timer {
}

TimerLoggingAspect方面

@Aspect
@Component
public class TimeLoggingAspect {

@Pointcut("annotation(@org.my.pckg.annotation.Timer)")
public void loggingPointCutDefinition(){}

    @Around("loggingPointCutDefinition()")
    public void userAdvice(ProceedingJoinPoint joinPoint) throws Throwable{
        createJsonString(joinPoint);
        joinPoint.proceed();
    }

    private String createJsonString(ProceedingJoinPoint joinPoint) {
    //logic for creating and printing json
        return "";
    }
}

配置类

package org.my.pckg.config;
@Configuration
@EnableAspectJAutoProxy  
@ComponentScan(basePackages =     {"org.my.pckg.utilities","org.my.pckg.annotation"})
public class AssetConfig {

    @Bean
    public TimeLoggingAspect timeLoggingAspect() {
        return new TimeLoggingAspect();
    }
}

示例测试控制器

package org.my.pckg;
@SpringBootApplication
@PropertySources({
    @PropertySource(value = "classpath:application.properties", ignoreResourceNotFound = true)
})
@Configuration
@ComponentScan(basePackages = {"org.my.pckg.config","org.my.pckg.annotation"})
@RestController
@EnableAutoConfiguration
@EnableAspectJAutoProxy
public class Example {

@Timer
@RequestMapping("/")
String home() {
    return "Hello World!";
}

public static void main(String[] args) throws Exception {
    SpringApplication.run(Example.class, args);
}
}

application.properties包含以下内容:

spring.aop.proxy-target-class=true

使用以下设置时,我使用以下方式调试应用程序:

spring-boot:run "-Drun.jvmArguments=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5005"

如果我更改了切入点,则不执行Aspect 来自@Around("@annotation(org.my.pckg.annotation.Timer)")  到@Around("execution( * org.my.pckg.*.*(..))") 它完美无缺!

请帮助找出定义自定义注释时缺少的内容..

2 个答案:

答案 0 :(得分:2)

从以下位置更改切入点:

@Pointcut("execution(@org.my.pckg.annotation.Timer)")

要:

@Pointcut("@annotation(org.my.pckg.annotation.Timer)")

阅读Declaring a Pointcut上的Spring文档。

答案 1 :(得分:0)

经过多次反复试验后,我找到了解决上述问题的方法。

创建一个文件aop.xml并将其放在resource / META-INF /中,内容如下

[NPoco.Reference(NPoco.ReferenceType.Foreign, ColumnName = "SchoolId", ReferenceMemberName = "SchoolId")]
public School CurrentSchool { get; set; }

感谢http://foat.me 在此处查找更详细的解决方 http://foat.me/articles/java-aspects-using-spring-aop-and-aspectj/#internal-method-calls