LoginSignup
0
0

More than 1 year has passed since last update.

SpringAOPでログ出してみた

Last updated at Posted at 2022-06-05

Spring AOP

本ページについて

「Spring徹底入門」を読んでいるところで、
気になっていたコア機能の1つであるAOPを試してみた。

前提

AOPを実現するために依存性を追加する。

pom.xml/dependency

<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-context</artifactId>
</dependency>
<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-aop</artifactId>
</dependency>
<dependency>
	<groupId>org.aspectj</groupId>
	<artifactId>aspectjweaver</artifactId>
</dependency>

実装

DIコンテナに格納されたBeanに対してProxyオブジェクトなるもので、Aopソースで設定したAdviceなるものを設定する、とのこと。
また、@Configuration定義ファイルに、Aopを実行可能なアノテーションを追記するらしい。

Controller

@GetMapping("/order")
public String getOrder() {
    return aopService.getOd();
}   

AppConfig

@Configuration
@ComponentScan("com.example")
@EnableAspectJAutoProxy
public class AppConfig {
    @Bean    
    AopService aopService() {
        return new AopService();
    }
}

AOP

@Aspect
@Component
public class MethodStartLoggingAspect {
    
    Logger log = LoggerFactory.getLogger(MethodStartLoggingAspect.class);

    @Before("execution(* *..*AopService.*(..))")
    public void logBeforeXxx(JoinPoint jp) throws IOException {
        log.info("メソッド開始" + jp.getSignature());
    }
}

実行結果

リクエスト実行

$ curl http://localhost:8080/order

コンソールログ

2022-06-05 11:56:26.296  INFO 11874 --- [nio-8080-exec-1] c.e.a.aop.MethodStartLoggingAspect       : メソッド開始String com.example.aopdemo.domain.AopService.getOd()

感想

  • AOPを実行させたい対象はDIコンテナにBeanとして登録済みである必要がある
  • Java Configurationファイルの作成は、普段は作成していないためなれなかった
  • Pointcut式なるものが、独特な書式
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0