[英]Spring AOP with custom annotation not working
I have looked at every example on stack exchange and on spring's example website and everything seems like this should work. 我已经查看了堆栈交换和Spring的示例网站上的每个示例,并且似乎一切正常。 I must be missing something simple
我一定缺少简单的东西
I have a custom annotation that ideally I would like to apply on either all methods of a class if the class is annotated or on any method annotated. 我有一个自定义批注,理想情况下,如果要对类进行批注,则我希望将其应用于类的所有方法,或者对任何方法进行批注。 Here is the aspect, test, and code:
这是方面,测试和代码:
Annotation 注解
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
@Target({METHOD})
@Retention(RUNTIME)
public @interface Monitor {
String value() default "Monitor";
}
Aspect 方面
@Aspect
@Component
public class LatencyAspect {
@Autowired
private Logger logger;
@Around("@annotation(Monitor)")
public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
Object retVal = joinPoint.proceed();
logger.info("logged");
return retVal;
}
}
Test 测试
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader = AnnotationConfigContextLoader.class,classes = {LatencyConfig.class, LatencyTest.ContextConfiguration.class})
@ComponentScan
public class LatencyTest {
final static Logger log = mock(Logger.class);
@Autowired
private SomeClass someClass;
@Test
public void testExample() throws Exception {
someClass.doSomething("foo");
verify(log).info("logged");
}
@EnableAspectJAutoProxy(proxyTargetClass = true)
@Configuration
static class ContextConfiguration {
@Bean
public SomeClass properties() {
return new SomeClass();
}
@Bean
public Logger log() {
return log;
}
}
public static class SomeClass {
@Monitor
@Transient
public String doSomething(String whatever) {
return "done";
}
}
}
Result 结果
Wanted but not invoked:
logger.info("logged");
-> at org.bongiorno.latency.LatencyTest.testExample(LatencyTest.java:74)
Actually, there were zero interactions with this mock.
Links 链接
Spring doesn't pick up the @ComponentScan
annotation from a JUnit test class. Spring不会从JUnit测试类中获取
@ComponentScan
批注。 Move the annotation to your LatencyConfig
class or the test-local LatencyTest.ContextConfiguration
inner configuration class. 将注释移至您的
LatencyConfig
类或测试本地的LatencyTest.ContextConfiguration
内部配置类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.