In this post, I would demo how to solve error Type referred to is not an annotation type when using Spring AOP.
- SpringBoot 2
- java 1.8+
- AspectJ Tools 1.9.4
3. The POM
We only use the SpringBoot 2 and AspectJ 1.9.4 , the POM is as follows:
4. The Code
We want to use Spring AOP to add logging ability to SpringBoot web controllers, the code is as follows:
You can see that, this controller just simply returns a string, the url is http://localhost:8080/hello
The Spring AOP Aspect:
Run the code, we got the error message:
5.Why did this error happen?
we had this error because we misused the Within expression,according to spring aop documents, When we define the pointcut by using within, there are following usages examples:
- any join point (method execution only in Spring AOP) within the service package:
- any join point (method execution only in Spring AOP) within the service package or a sub-package:
- any join point (method execution only in Spring AOP) where the declared type of the target object has an @Transactional annotation:
Here we used the Within like this:
- @Around(“within(@com.bswen.testspringaop.controllers.HelloController *)”)
It would let spring to find the class with annotation @HelloController, and because no class is annoatated by it, so there is an error.
6.How to solve this problem?
We should change the pointcut expression to this:
This means any class under com.bswen.testspringaop.controllers package should be instrumented.
Run the code, we get this:
Be careful if you want to use Within in spring aop pointcut expressions.