使用:Spring Boot::(v1.2.8.RELEASE)
我已经在 build.gradle 中使用 aop starter 设置了一个 Spring Boot 应用程序
compile("org.springframework.boot:spring-boot-starter-aop")
我已经检查过并且正在获取依赖项:
| | | | +--- org.springframework:spring-aop:4.1.9.RELEASE
| | | | | +--- aopalliance:aopalliance:1.0
这是 AspectConfig:
@Configuration
@ComponentScan
@EnableAspectJAutoProxy
public class AspectConfig {
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}
我已将 Configuration 类放置在应用程序层次结构的底部,以便组件扫描仅覆盖整个应用程序。这都是原型(prototype)代码,但它最终将形成入门模块的一部分,扫描所有区域的能力会很有帮助。
现在我定义了一个注释:
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface AutowiredRestTemplate {
String name();
String methodUrl();
}
并有一个测试方法:
@Component(value = "testGateway")
public class TestGatewayImpl implements TestGateway {
private static final Logger LOG = LoggerFactory.getLogger(TestGatewayImpl.class);
AuspostRestTemplate restTemplate;
@AutowiredRestTemplate(name = "locations", methodUrl = "/fishing")
public Response doWork() {
LOG.debug("Got into gateway with restTemplate {}", restTemplate);
return restTemplate.getForObject(Response.class);
}
}
现在的建议是:
@Aspect
@Component
public class AutowiredRestTemplateAspect {
@Autowired
Map<String, AuspostRestTemplate> restTemplateMap;
@Autowired
private ApplicationContext context;
@Pointcut("execution(public * *(..))")
public void anyPublicMethod(){}
@Around("anyPublicMethod() && @annotation(autowiredRestTemplate)")
public Object inAnyMethod(ProceedingJoinPoint pjp, AutowiredRestTemplate autowiredRestTemplate) throws Throwable{
AuspostRestTemplate restTemplate = restTemplateMap.get(autowiredRestTemplate.name());
restTemplate.setMethodUrl(autowiredRestTemplate.methodUrl());
pjp.getTarget().getClass().getDeclaredField("restTemplate").set(pjp.getTarget(),restTemplate);
return pjp.proceed();
}
}
问题是,当 doWork()
方法运行时,建议永远不会被触发。从日志来看,似乎切入点甚至没有设置。谁能看出这里出了什么问题吗?
编辑:我已经为我想要使用的注释添加了配置以及保留和目标注释(在这个问题的上方)。 编辑2:更改了配置类上的ComponentScan,因为其他事情很复杂并且无论如何都不起作用。
最佳答案
您是否尝试将 @EnableAspectJAutoProxy(proxyTargetClass=true)
放在您的配置类上?
关于java - 带有 Spring Boot 建议的 AOP 未触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37200764/