Java 在建议没有得到执行之前

Java 在建议没有得到执行之前,java,spring,aop,Java,Spring,Aop,我试图调用before建议,但使用定义的切入点不会执行相同的建议 我的主要应用在com.my.ms包中 @SpringBootApplication @EnableAspectJAutoProxy public class TemplateServiceApplication { public static void main(String[] args) { SpringApplication.run(TemplateServiceApplication.class, args);

我试图调用before建议,但使用定义的切入点不会执行相同的建议

我的主要应用在com.my.ms包中

@SpringBootApplication
@EnableAspectJAutoProxy
public class TemplateServiceApplication {

public static void main(String[] args) {

    SpringApplication.run(TemplateServiceApplication.class, args);
}

}
在com.my.ms.tst.advices包中,我有之前的建议

@Aspect
public class ValidatingAdvices {

@Before(value = "execution(* com.my.ms.tst.api.*.get*(..))")
public void validateKey(JoinPoint joinPoint) throws Throwable {
     System.out.println("Executing the before advice");
 }

}
控制器位于com.my.ms.tst.api包中

@Controller
@RequestMapping("/ts")
public class MainController {



@GetMapping("/check")
public String getTemp() throws IOException {

    return "five";
}

}

但是下面的建议没有得到执行

如果您在验证建议中添加@Configuration注解

   @Configuration
    @Aspect
    public class ValidatingAdvices {

    @Before(value = "execution(* com.my.ms.tst.api.*.get*(..))")
    public void validateKey(JoinPoint joinPoint) throws Throwable {
         System.out.println("Executing the before advice");
     }

    }

您也可以使用@Component而不是@Configuration,或者如果您已经使用了@Component类,那么也可以,但请确保like ValidatingAdvices类不必使用@Bean。以供更多参考

@Component // @Configuration
@Aspect
public class ValidatingAdvices {

@Before(value = "execution(* com.my.ms.tst.api.*.get*(..))")
public void validateKey(JoinPoint joinPoint) throws Throwable {
     System.out.println("Executing the before advice");
 }

}

这会有什么影响?答案没有多大意义。你试过吗。我已经用那个变更执行了代码。它工作得很好。当然我会试试这个,当我输入完整的方法名时,它工作得很好,但是当我使用get*时,它不是!!。感谢您尝试以上操作。
@Configuration
注释应该转到
TemplateServiceApplication
,那里实际上有一些配置。把它放在方面是违反直觉的,甚至是混淆。方面没有配置任何东西。你们应该试着理解SpringAOP,而不仅仅是玩弄和使用任何似乎有效的东西,甚至不理解为什么。实际上Spring并不扫描Aspect类。这就是为什么我们把@Configuration放在这里。没有足够的信息来得出结论性的答案。但是如果您的方面没有作为bean/组件实例化,那么您应该通过向方面类添加
@component
注释来帮助Spring的组件扫描器找到它。