I created a demo application to reproduce it:
DemoService
open class DemoService {
fun test() {
println("test function is executed.")
}
}
DemoAspect
@Aspect
class DemoAspect {
@Around("execution(* com.example.demo.service.DemoService.test(..))")
fun testAspect(joinPoint: ProceedingJoinPoint) {
println("before test function.")
joinPoint.proceed()
println("after test function.")
}
}
AppConfig
@Configuration
@EnableAspectJAutoProxy
class AppConfig {
@Bean
fun demoService() = DemoService()
@Bean
fun demoAspect() = DemoAspect()
}
SpringDemoApplication
@SpringBootApplication
@Import(AppConfig::class)
class SpringDemoApplication
fun main(args: Array<String>) {
val context = runApplication<SpringDemoApplication>(*args)
val demoService = context.beanFactory.getBean(DemoService::class.java)
demoService.test()
}
Execution result:
test function is executed.
The aspect is not working which is not expected.
I tried following variations and they worked correctly:
Remove the beans in configuration services and register beans by annotations
DemoService
@Service
open class DemoService {
...
}
AppConfig
@Configuration
@EnableAspectJAutoProxy
class AppConfig {
@Bean
fun demoAspect() = DemoAspect()
}
Let DemoService
implements an interface
DemoService
interface DemoService {
fun test()
}
open class DemoServiceImpl: DemoService {
override fun test() {
println("test function is executed.")
}
}
AppConfig
@Configuration
@EnableAspectJAutoProxy
class AppConfig {
@Bean
fun demoService() = DemoServiceImpl()
@Bean
fun demoAspect() = DemoAspect()
}
I want to understand why the AspectJ is not working on this combination:
- The target bean is not implementing any interface.
- The bean is registered in Configuration class.