--I want to test if the AOP settings are working ――However, it is difficult to test if you are performing processing that causes side effects to the outside (eg transaction, log output ... etc). --Proxy Factory is convenient in such a case
Prepare the following Service class and MethodInterceptor as a prerequisite.
AOP target Service
@Service
class SampleService {
fun execute() {
println("SampleService#execute")
}
}
Interceptor
class SampleInterceptor(
private val name: String
) : MethodInterceptor {
override fun invoke(invocation: MethodInvocation?): Any? {
println("intercept by $name")
return invocation?.proceed()
}
}
class SampleServicePointCut : StaticMethodMatcherPointcut() {
override fun matches(method: Method, @Nullable targetClass: Class<*>?): Boolean {
return targetClass?.let { SampleService::class.java.isAssignableFrom(it) } ?: false
}
}
config
@Configuration
@EnableAspectJAutoProxy(proxyTargetClass = true)
class AopConfig {
@Bean
fun interceptorA(): Advisor {
return DefaultPointcutAdvisor(SampleServicePointCut(), SampleInterceptor("configured interceptor"))
}
}
Test code
@SpringBootApplication
class SpringTestApplication
@RunWith(SpringRunner::class)
@SpringBootTest(classes = [SpringTestApplication::class])
internal class SampleServiceTest {
@Autowired
private lateinit var service: SampleService
@Test
fun test() {
service.execute()
}
}
Execution result
intercept by configured interceptor
SampleService#execute
Test code using ProxyFactory
@Test
fun testByProxy() {
val factory = ProxyFactory(SampleService())
factory.addAdvisor(DefaultPointcutAdvisor(SampleServicePointCut(), SampleInterceptor("Proxy")))
val proxy = factory.proxy as SampleService
proxy.execute()
}
Execution result
intercept by Proxy
SampleService#execute
It is also good to create a util function using Extension.
Example using kotlin extension Test code using ProxyFactory
@Test
fun testByProxy() {
val proxy = SampleService().proxy {
addAdvisor(DefaultPointcutAdvisor(SampleServicePointCut(), SampleInterceptor("Proxy")))
}
proxy.execute()
}
@Suppress("UNCHECKED_CAST")
fun <T : Any> T.proxy(settings: ProxyFactory.() -> Unit): T {
return ProxyFactory(this).also { settings(it) }.proxy as T
}
Service and Config
@Aspect
@Component
class SampleAspect(
private val name: String = ""
) {
@Before("execution(* SampleAspectService.*(..))")
fun advice() {
println("advice by $name")
}
}
@Service
class SampleAspectService {
fun execute() {
println("SampleAspectService#execute")
}
}
Test code
@Test
fun testAspectProxy() {
val factory = AspectJProxyFactory(SampleAspectService())
factory.addAspect(SampleAspect("proxy"))
val proxy = factory.getProxy() as SampleAspectService
proxy.execute()
}
Execution result
advice by proxy
SampleAspectService#execute
Recommended Posts