Spring Boot
[Spring Boot] AOP(Aspect Oriented Programming) ์ ์ฉํ๊ธฐ
hnev
2022. 10. 24. 22:31
๐ AOP(Aspect Oriented Programming)๋?
์ด๋ค ๋ก์ง์ ๊ธฐ์ค์ผ๋ก ํต์ฌ์ ์ธ ๊ด์ , ๋ถ๊ฐ์ ์ธ ๊ด์ ์ผ๋ก ๋๋ ๋ณด๊ณ ๊ทธ ๊ด์ ์ ๊ธฐ์ค์ผ๋ก ๊ฐ๊ฐ ๋ชจ๋ํ ํ๋ค.
- ํต์ฌ์ ์ธ ๊ด์ : ๊ฐ๋ฐ์๊ฐ ์ ์ฉํ๊ณ ์ ํ๋ ํต์ฌ ๋น์ฆ๋์ค ๋ก์ง.
- ๋ถ๊ฐ์ ์ธ ๊ด์ : ํต์ฌ ๋ก์ง์ ์ํํ๊ธฐ ์ํด ํ์ํ DB ์ฐ๊ฒฐ(JDBC), ํ์ผ ์ ์ถ๋ ฅ, ๋ก๊น
build.gradle
implementation 'org.springframework.boot:spring-boot-starter-aop'
Enable AOP
@EnableAspectJAutoProxy
Appplication ํด๋์ค์ ํด๋น ์ด๋
ธํ
์ด์
์ ์ถ๊ฐํ๋ค.
@EnableAspectJAutoProxy
@SpringBootApplication
public class AopApplication {
public static void main(String[] args) {
SpringApplication.run(AopApplication.class, args);
}
}
@Around("execution(์ ์ฉํ ๊ท์น ์์ฑ)")
1. ์ ๊ทผ ์ ํ์ ํจํด
โช public [์๋ต ๊ฐ๋ฅ]
2. ๋ฆฌํด ํ์
ํจํด
โช long
3. ํจํค์ง๋ช
, ํด๋์ค ๊ฒฝ๋ก ํจํด
โช com.admin.service.TestService [์๋ต ๊ฐ๋ฅ]
4. ๋ฉ์๋๋ช
ํจํด(ํ๋ผ๋ฏธํฐ ํ์
ํจํด 1|ํ๋ผ๋ฏธํฐ ํ์
ํจํด 2)
โช save(String, String)
5. throws ์์ธ ํ์
ํจํด
โช throws RuntimeException [์๋ต ๊ฐ๋ฅ]
*๋ ๋ชจ๋ ๊ฐ์ ํ์ฉํฉ๋๋ค.
@Around("execution(* com..service.*Service.save*(..))") ์ ๊ฐ์ด ์์ฑ ํ ๊ฒฝ์ฐ
โช com.*.service ํจํค์ง์ *Service๋ก ๋๋๋ ํด๋์ค์์ save๋ก ์์ํ๋ ๋ฉ์๋ ํ๋ผ๋ฏธํฐ ๊ตฌ๋ถ ์์ด ์ ์ฉ๋ฉ๋๋ค.
@Slf4j
@Aspect
@Component
public class LogAspect {
@Around("execution(* com..service.*Service.save*(..))")
public Object saveLogging(ProceedingJoinPoint pjp) throws Throwable {
Object result = pjp.proceed();
log.info("==> LogAspect saveLogging Root : {}", pjp.getSignature().getDeclaringTypeName());
log.info("==> LogAspect saveLogging Method : {}", pjp.getSignature().getName());
return result;
}
}
ํ ์คํธ
[io-20020-exec-6] com.admin.aspect.LogAspect : ==> LogAspect saveLogging Root : com.admin.service.TestService
[io-20020-exec-6] com.admin.aspect.LogAspect : ==> LogAspect saveLogging Method : saveTest
์๋ฌ
์กด์ฌํ์ง ์๋ ๊ฒฝ๋ก์ ํด๋์ค, ๋น, ์๋ชป๋ ํจํด์ ์ ์ฉํ๋ฉด ์๋์ ๊ฐ์ ๋ฉ์์ง๊ฐ ์ถ๋ ฅ๋๋ค.
์ด๋ด ๊ฒฝ์ฐ @Around์ ์์ฑํ ๋ด์ฉ์ ๋ค์ ํ์ธํด๋ณธ๋ค.
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration': Initialization of bean failed; nested exception is java.lang.IllegalArgumentException: warning no match for this type name: com.service.service [Xlint:invalidAbsoluteTypeName]