AspectJ和Kotlin - 注入Spring服务

时间:2018-02-13 21:48:54

标签: spring kotlin aspectj

ember-cli: 2.18.2
node: 6.11.1

这段代码给了我这个堆栈跟踪:

@Aspect
@Component
class ExceptionAspect(private val mailSenderServiceImpl: MailSenderServiceImpl)
{
    @AfterThrowing(pointcut = "execution(* myproject.mail..*(..))", throwing = "throwable")
    fun sendError(throwable: Throwable)
    {
    mailSenderServiceImpl.send(recipient = "email@gmail.com", subject = "Exception", content = "We have got a problem here!")
    }
}

我尝试使用lateinit var将其注入到字段中,或者默认情况下将其设置为null,但是我没有成功(NPE,如果是lateinit - 告诉我该字段尚未初始化...)。可以做些什么呢?

谢谢!

我做了一个重现问题的最小例子: write a custom Collector

1 个答案:

答案 0 :(得分:0)

我必须在配置类中声明一个方面Bean并使用aspectOf(),同时在方面的服务上添加@Inject(或@Autowired)。就是这样。

@EnableLoadTimeWeaving(aspectjWeaving = EnableLoadTimeWeaving.AspectJWeaving.ENABLED)
@Configuration
open class AspectConfiguration : LoadTimeWeavingConfigurer
{
   override fun getLoadTimeWeaver(): LoadTimeWeaver = InstrumentationLoadTimeWeaver()

   @Bean
   open fun aspect(): ExceptionAspect = Aspects.aspectOf(ExceptionAspect::class.java)
}