前回の続き。サンプルコードは前回のものをベースに少し変更する。
フォルダ構成だけ再掲。
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 FrameworkによるJavaアプリケーション開発
- 作者:株式会社NTTデータ
- 出版社/メーカー: 翔泳社
- 発売日: 2016/07/21
- メディア: 大型本

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