山崎屋の技術メモ

IT業界で働く中でテクノロジーを愛するSIerのシステムエンジニア👨‍💻 | AndroidとWebアプリの二刀流🧙‍♂️ | コードの裏にあるストーリーを綴るブログ執筆者✍️ | 日々進化するデジタル世界で学び続ける探究者🚀 | #TechLover #CodeArtisan、気になること、メモしておきたいことを書いていきます。

【Spring Framework】component-scanのいろいろ②

前回の続き。サンプルコードは前回のものをベースに少し変更する。

フォルダ構成だけ再掲。
f:id:yyama1556:20160810173038p:plain

applicationContext.xml 内の [context:component-scan] タグを以下のようにすることで、Fuga クラスも Piyo クラスも Spring コンテナに登録されないことを確認した。

<context:component-scan base-package="org.yyama.hoge"
		use-default-filters="false" />

この状態から [context:include] タグを使って、一部のクラスだけを登録するようにしたい。

アノテーションを指定して登録する

Fuga クラスには @Component アノテーションが付与されている。Piyo クラスには @Service アノテーションが付与されている。

では、ベースパッケージ(org.yyama.hoge)配下の @Service アノテーションが付与されたクラスだけをロードするように変更したい。

applicationContext.xmlを修正する。

<?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"
	xsi:schemaLocation="
      http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans.xsd
      http://www.springframework.org/schema/context
      http://www.springframework.org/schema/context/spring-context.xsd">
	<context:component-scan base-package="org.yyama.hoge"
		use-default-filters="false">
		<context:include-filter type="annotation"
			expression="org.springframework.stereotype.Service" />
	</context:component-scan>
</beans>

[context:include-filter] タグの type に "annotation" を指定することにより、expression で指定したアノテーションが付与されているクラスだけをコンテナに登録するよう指示している。

実行すると期待通り Piyo クラスだけ登録されていることが確認できる。

piyo

じゃあ、include-filter を次のようにすると、Fuga クラスだけ登録されるのだろうか。

		<context:include-filter type="annotation"
			expression="org.springframework.stereotype.Component" />

残念ながら、@Service アノテーションは @Component アノテーションを含んでいるので、Fuga クラスだけでなく Piyo クラスも登録される。詳しくは、本家の Javadoc を確認しよう。

登録するクラスを正規表現で指定する。

正規表現で登録するクラスを指定することもできる。その場合、[context:include-filter] タグの type に "regex" を指定し、expression に正規表現を指定する。

		<context:include-filter type="regex"
			expression="org\.yyama\.hoge\.F.*" />

実行結果。

fuga

正規表現を指定する場合、Fura クラスの @Component アノテーションは、記述しなくても構わない。

package org.yyama.hoge;

import org.springframework.stereotype.Component;

@Component // ←←← 無くても良い
public class Fuga {
}

その他のtype

[context:include-filter] タグの type には、そのほかにも、assignable/aspectj/custom が指定できる。詳しくは リファレンスマニュアル を参照して欲しい。

今日はここまで。

続きは
【Spring Framework】component-scanのいろいろ③ - 山崎屋の技術メモ


Spring 関連記事へのリンク集つくりました。


Spring徹底入門 Spring FrameworkによるJavaアプリケーション開発

Spring徹底入門 Spring FrameworkによるJavaアプリケーション開発

Spring Framework 5 プログラミング入門

Spring Framework 5 プログラミング入門

  • 作者:掌田 津耶乃
  • 出版社/メーカー: 秀和システム
  • 発売日: 2017/12/20
  • メディア: 単行本