AnnotationBeanConfigurerAspect是一个AspectJ切面,使用AspectJ语言定义。
通过上下文获取该切面后,调用其实例方法configureBean()
,可对一个使用new关键字创建的对象进行配置,实现自动连线。
该切面属于制品spring-aspects
:
dependencies {
implementation ‘org.jetbrains.kotlin:kotlin-stdlib‘
implementation ‘org.springframework:spring-context:5.2.0.RELEASE‘
implementation ‘org.springframework:spring-aspects:5.2.0.RELEASE‘
}
configureBean():
package bean
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.annotation.Configurable
import org.springframework.beans.factory.aspectj.AnnotationBeanConfigurerAspect
import org.springframework.context.ApplicationContext
import org.springframework.context.annotation.ComponentScan
import org.springframework.stereotype.Component
import org.springframework.test.context.junit.jupiter.SpringExtension
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig
@Component
@Configurable(preConstruction = true)
open class A {
@Autowired
open var ctx: ApplicationContext? = null
open fun foo() {
println(ctx)
}
}
@ExtendWith(SpringExtension::class)
@SpringJUnitConfig(ConfigurableTest::class)
@ComponentScan
@org.springframework.context.annotation.aspectj.EnableSpringConfigured
open class ConfigurableTest {
@Autowired lateinit var ctx: ApplicationContext
@Test fun main() {
A().foo() // null
ctx.getBean(A::class.java).foo() // not null
val aspect = ctx.getBean(AnnotationBeanConfigurerAspect::class.java)
val bean = A()
bean.foo() // null
aspect.configureBean(bean)
bean.foo() // not null
}
}
原文:https://www.cnblogs.com/develon/p/14613498.html