![](/img/trans.png)
[英]Intercept ThreadContext of log4j2 in Spring AOP Around Advice
[英]Unable to intercept the advice method in Spring AOP
我正在使用 Spring AOP 實現自定義注釋處理。 我有以下代碼。
public class CacheDemo {
private static ApplicationContext applicationContext;
public static void main(String args[])
{
applicationContext =
new AnnotationConfigApplicationContext(ApplicationConfiguration.class);
}
}
//應用配置
@Configuration
@ComponentScan("Demo")
@Component
public class ApplicationConfiguration implements ApplicationContextAware {
@Autowired
TestCacheDemo testCacheDemo;
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext ctx) throws BeansException {
applicationContext = ctx;
}
@Bean
public void testCacheDemoIntialize()
{
testCacheDemo.setApplicationContext(applicationContext);
testCacheDemo.test();
}
}
//CustomAnnotation處理器
@Aspect
@Component
public class CustomAnnotationAspect {
@Autowired
private AbstractCacheService cacheService;
@Around("@annotation(Demo.CustomCacheable)")
public Object customCacheable(ProceedingJoinPoint joinPoint) throws Throwable { // This method is not called at all
joinPoint.proceed();
// Some other code to follow
}
// 自定義注解
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface CustomCacheable {
}
// 注解用戶
@Component
public class CacheProvider
{
@Autowired
AbstractCacheService abstractCacheService;
CacheManager<String,String> cacheManager;
@PostConstruct
void init()
{
cacheManager = CreateCache.create(s -> {return s.toUpperCase();});
abstractCacheService.setCacheManager(cacheManager);
}
@CustomCacheable
String getCacheValue(String s)
{
String str=s.toUpperCase();
return str;
}
}
出於測試目的,我創建了下面的 bean
@Component
public class TestCacheDemo extends TimerTask
{
private ApplicationContext applicationContext;
private Timer timer;
@Autowired
CacheProvider cacheProvider;
void test()
{
System.out.println("Called test");
for (String beanName : applicationContext.getBeanDefinitionNames()) {
System.out.println(beanName);
}
//CacheProvider cacheProvider = applicationContext.getBean(CacheProvider.class);
//cacheProvider.getCacheValue("Hello");
timer = new Timer();
timer.schedule(this,1000,3000);
}
void setApplicationContext(ApplicationContext ctx)
{
applicationContext=ctx;
}
@Override
public void run() {
cacheProvider.getCacheValue("Hi");
}
}
每當應用程序啟動時,它都會調用 TestCacheDemo Class 的測試方法,並將計時器設置為在 3 秒后觸發,以便我可以從計時器任務的運行方法內部調用帶注釋的方法 getCacheValue。 但是當調用帶注釋的方法時,不會調用注釋處理器。 因此我無法進行注釋處理。 請讓我知道問題出在哪里?
要在 spring 啟動時使用 AspectJ,您必須啟用它。 您應該將以下注釋添加到您的應用程序主 class (CacheDemo) 或應用程序配置 class。
@EnableAspectJAutoProxy
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.