タイトル
 メニューにないコーナーはTopからいけます
TOPJavaspring → This Page

3.2.6.(Entity Manager)(AOPの利用) Spring+MVC+DB+Test構築サンプル

前提

このページに記載している内容は 2018/10/20 に書かれたものです。
掲載している画面や方法が将来的に変更されている場合があります。
また、掲載しているインストール方法は Windows 8.1 の場合です。
開発環境は
・Windows 8.1
・JDK 8
・STS(Spring Tool Suite) 3.9.5
・PostgreSQL 9.5.14
とします。

本ページは先に以下の7ページの内容を実施してからの内容となります。
1.準備
2.共通部分構築
3.2.1.Entity Manager 単一テーブルのCRUD
3.2.2.Entity Manager N:1テーブルのCRUD+自由なクエリ
3.2.3.Entity Manager 複合主キーテーブルのCRUD
3.2.4.Entity Manager 複数テーブルの結合+NativeQuery
3.2.5.Entity Manager トランザクション制御+エラーページ

AOP(Aspect-Oriented Programming)(アスペクト指向プログラミング)自体の解説はしません。
そこは自分で勉強して下さい。


目次

1.POM.xml編集
2.application-config.xml編集
3.AOPクラスの作成
4.確認実行

1.pom.xml編集(PostgreSQL追加)

まずは「pom.xml」を編集して「Maven」に「AOP」の利用に必要なライブラリを揃えてもらいます。
プロジェクト直下にある「pom.xml」をダブルクリックして開きます。
開いたら下のタブを「pom.xml」に切り替えます(最初からpom.xmlになっている場合もあります)
図:pom.xml

以下の内容に書き換えて保存しましょう。
赤文字が前回から追加になる箇所です。
保存すると必要なライブラリのダウンロードやビルドが始まるのでしばらく待ちましょう。

<project
	xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
		http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>jp.mitchy</groupId>
	<artifactId>WebDbSample2EntityManager</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>

	<properties>

		<!-- Generic properties -->
		<java.version>1.8</java.version>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		
		<!-- Web -->
		<jsp.version>2.2</jsp.version>
		<jstl.version>1.2</jstl.version>
		<servlet.version>3.1.0</servlet.version>
		
		<!-- Spring -->
		<spring-framework.version>5.0.2.RELEASE</spring-framework.version>

		<!-- Hibernate / JPA -->
		<hibernate.version>5.2.4.Final</hibernate.version>
		
		<!-- aspectj -->
		<aspectjrt-version>1.8.10</aspectjrt-version>
		
		<!-- Logging -->
		<logback.version>1.2.3</logback.version>
		<slf4j.version>1.7.25</slf4j.version>

		<!-- Test -->
		<junit.version>4.12</junit.version>

	</properties>
	
	<dependencies>
	
		<!-- Spring MVC -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${spring-framework.version}</version>
		</dependency>
		
		<!-- Other Web dependencies -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>${jstl.version}</version>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>${servlet.version}</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet.jsp</groupId>
			<artifactId>jsp-api</artifactId>
			<version>${jsp.version}</version>
			<scope>provided</scope>
		</dependency>
	
		<!-- Spring and Transactions -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-tx</artifactId>
			<version>${spring-framework.version}</version>
		</dependency>

		<!-- Logging with SLF4J & LogBack -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>${slf4j.version}</version>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>ch.qos.logback</groupId>
			<artifactId>logback-classic</artifactId>
			<version>${logback.version}</version>
			<scope>runtime</scope>
		</dependency>

		<!-- Hibernate -->
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-entitymanager</artifactId>
			<version>${hibernate.version}</version>
		</dependency>
		
		
		<!-- postgreSQL -->
		<dependency>
			<groupId>org.postgresql</groupId>
			<artifactId>postgresql</artifactId>
			<version>9.4-1206-jdbc42</version>
		</dependency>
		
		<!-- Spring JDBC -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>${spring-framework.version}</version>
		</dependency>
		
		<!--  Spring Data JPA -->
		<dependency>
			<groupId>org.springframework.data</groupId>
			<artifactId>spring-data-jpa</artifactId>
			<version>1.11.6.RELEASE</version>
		</dependency>
		
		<!-- Spring ORM -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-orm</artifactId>
			<version>${spring-framework.version}</version>
		</dependency>
		
		
		<!-- AspectJ -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-aop</artifactId>
			<version>${spring-framework.version}</version>
		</dependency>
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjrt</artifactId>
			<version>${aspectjrt-version}</version>
		</dependency>
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjweaver</artifactId>
			<version>${aspectjrt-version}</version>
		</dependency>
		
		
		<!-- Test Artifacts -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>${spring-framework.version}</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>${junit.version}</version>
			<scope>test</scope>
		</dependency>

	</dependencies>	
</project>


2.application-config.xml編集

application-config.xml にAOP関連情報を設定します。
/src/main/resources/spring
フォルダにある
application-config.xml
をダブルクリックして開きましょう。
開いたら下のタブを「Source」にします。
(最初から「Source」になっている場合もあります)
図:STS

以下の内容に書き換えて保存しましょう。
赤文字が前回から追加になる箇所です。
<?xml version="1.0" encoding="UTF-8"?>

<beans
	xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:jpa="http://www.springframework.org/schema/data/jpa"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:jdbc="http://www.springframework.org/schema/jdbc"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
		http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/data/jpa
		http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
		http://www.springframework.org/schema/tx 
		http://www.springframework.org/schema/tx/spring-tx.xsd
		http://www.springframework.org/schema/aop
		http://www.springframework.org/schema/aop/spring-aop.xsd
		http://www.springframework.org/schema/jdbc
		http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
		http://www.springframework.org/schema/context
		http://www.springframework.org/schema/context/spring-context.xsd">
	
	<context:property-placeholder location="classpath:jdbc.properties" />
	<context:annotation-config />
	<context:component-scan base-package="jp.mitchy"/>
	
	<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
	
	<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName" value="${jdbc.driverClassName}" />
		<property name="url" value="${jdbc.url}" />
		<property name="username" value="${jdbc.username}" />
		<property name="password" value="${jdbc.password}" />
	</bean>
	
	<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<property name="jpaVendorAdapter">
			<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
				<property name="showSql" value="false" />
				<property name="database" value="POSTGRESQL" />
			</bean>
		</property>
	</bean>
	
	<tx:annotation-driven transaction-manager="transactionManager"/>
	
	<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
		<property name="dataSource" ref="dataSource" />
	</bean>
	
	<aop:aspectj-autoproxy />
	<aop:config proxy-target-class="true" />
	
</beans>
<aop:aspectj-autoproxy />
はAspectJ のアノテーションを使うための設定です。

<aop:config proxy-target-class="true" />
はクラスにAOPを対応させるための設定です。
(これがないとインタフェースにしか対応しない)


3.AOPクラスの作成

次に横断的な処理をするクラスを作ります。
DAOの各種メソッドの開始と終了でログを出力する処理をさせてみましょう。
プロジェクト名を右クリックして「New」>「Class」を選択します。
図:STS

「New Java Class」ダイアログが表示されます。
・「Package」は「jp.mitchy.aop」と入力
・「Name」は「LogAspect」と入力
・それ以外の項目はそのまま
「Finish」ボタンを押します。
図:New Java Class

作成された「LogAspect.java」が開くので、内容を以下のように書き換えて保存しましょう。
package jp.mitchy.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

/**
 * DAOクラスのメソッド前後にAOPでログを出力するクラス
 */
@Component
@Aspect
public class LogAspect {

	/**
	 * メソッド実行前にログを出力
	 * 
	 * @param joinPoint
	 */
	@Before("execution(* jp.mitchy.dao.impl.*Impl.*(..))")
	public void beforeLog(JoinPoint joinPoint) {
		System.out.println("---------- AOP Before ---------- S");
		System.out.println("Class :" + joinPoint.getTarget().getClass().getName());
		System.out.println("Method:" + joinPoint.getSignature().getName());
		String args = "args	 :";
		for ( Object obj : joinPoint.getArgs()) {
			args += obj + " ";
		}
		System.out.println(args);
		System.out.println("---------- AOP Before ---------- E");
	}
	
	/**
	 * メソッド実行後にログを出力
	 * 
	 * @param joinPoint
	 */
	@After("execution(* jp.mitchy.dao.impl.*Impl.*(..))")
	public void afterLog(JoinPoint joinPoint) {
		System.out.println("---------- AOP After  ---------- S");
		System.out.println("Class :" + joinPoint.getTarget().getClass().getName());
		System.out.println("Method:" + joinPoint.getSignature().getName());
		System.out.println("---------- AOP After  ---------- E");
	}
	
}
クラス名の上に @Component アノテーションをつけてコンポーネント化しています。
(Spring によって bean 登録される)
クラス名の上に @Aspect アノテーションもつけています。
これをつけることによって横断的な処理をさせるためのコンポーネントとして登録することができます。

beforeLog メソッドの上に @Before アノテーションをつけています。
これをつけることによって対象のメソッドが実行される前に
beforeLog メソッドが動作します。
@Before アノテーションの中で対象のクラスやメソッドを指定できます。
書式などは各自調べてみて下さい。
引数の JoinPoint からクラス・メソッドの名前や引数を取得することができます。

afterLog メソッドの上に @After アノテーションをつけています。
これをつけることによって対象のメソッドが実行された後に
afterLog メソッドが動作します。
@After アノテーションの中で対象のクラスやメソッドを指定できます。
書式などは各自調べてみて下さい。

以上で全ての対応が完了です。


4.確認実行

念のためにいつもの「Maven Clean」「Maven Install」をやっておきましょう。
エラーが出たら「Project」>「Clean」をやってから
再度「Maven Install」です。

次にプロジェクト名を右クリックして「Run As」>「Run On Server」を選択します。
図:STS

少し時間がかかりますが「Console」に状況が表示されていきます。
しばらくすると内蔵ブラウザが立ち上がり、下記の画面が表示されます。
図:ブラウザ

「Department Test」のリンクをクリックしてみましょう。
「Console」画面を見てみると
DepartmentDaoImpl の各種メソッドの前後でログが出力されていることが分かります。
図:ブラウザ

以上で Entity Manager を使ったAOPの利用の
サンプル構築は完了です。


ダウンロード

作成したプロジェクトのソースをダウンロードできます。
326WebDbSample2EntityManager.zip


更新履歴

2018/10/20 新規作成

TOPJavaspring → This Page
Valid CSS!