Spring注釈解説

8928 ワード

Spring注釈解説
来た:http://hanyexiaoxiao.iteye.com/blog/4101231. Spring注解を使って属性を注入します。 1.1.注を使う前に属性をどのように注入しましたか? クラスの実現:
public class UserManagerImpl implements UserManager {
	private UserDao userDao;
	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}
	...
}
設定ファイル:
<bean id="userManagerImpl" class="com.kedacom.spring.annotation.service.UserManagerImpl">
	<property name="userDao" ref="userDao" />
</bean>
<bean id="userDao" class="com.kedacom.spring.annotation.persistence.UserDaoImpl">
	<property name="sessionFactory" ref="mySessionFactory" />
</bean>
1.2@Autowiredの注釈を導入する(推奨しないので、@Resourceを使用することを推奨する) クラスの実現(メンバー変数を表示)
public class UserManagerImpl implements UserManager {
	@Autowired
	private UserDao userDao;
	...
}
または(方法を表示する)
public class UserManagerImpl implements UserManager {
	private UserDao userDao;
	@Autowired
	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}
	...
}
設定ファイル
<bean id="userManagerImpl" class="com.kedacom.spring.annotation.service.UserManagerImpl" />
<bean id="userDao" class="com.kedacom.spring.annotation.persistence.UserDaoImpl">
	<property name="sessionFactory" ref="mySessionFactory" />
</bean>
@Autowiredは、メンバー変数、方法、および構造関数を表示して、自動組立の仕事を完成することができます。以上の2つの異なる実施形態では、@Autowiredの表示位置が異なり、これらはSpringでuserManagerImplのbeanを初期化する時に、自動的にuserDaoという属性を組み立てます。違いは、最初の実装では、Springは直接UserDaoタイプの唯一のbean賦値をuserDaoというメンバー変数に与えます。第二の実施形態では、SpringはsetsUserDao方法を呼び出してUserDaoタイプの唯一のbeanをuserDaoという属性に組み立てる。 1.3.@Autowiredを働かせる @Autowiredを動作させるには、設定ファイルに以下のコードを追加する必要があります。
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />
1.4.@Qualfier @Autowiredは種類によって自動的に組み立てられている。上記の例では、Springコンテキストに一つ以上のUserDaoタイプのbeanが存在すると、BeanCreationException異常を投げます。SpringコンテキストにUserDaoタイプのbeanが存在しない場合は、BeanCreationException異常を投げます。これらの問題は@Qualfier配合@Autowiredを使って解決できます。 1.複数のUserDaoの例が存在する可能性がある。
	@Autowired
	public void setUserDao(@Qualifier("userDao") UserDao userDao) {
		this.userDao = userDao;
	}
このようにSpringはアメリカのbeanにidを見つけて組み立てます。 2.UserDaoの例がないかもしれません。
	@Autowired(required = false)
	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}
1.5.@Resource(JSR-250標準注、Spring特有の@Autowired注釈の代わりに使用することを推奨します。) Springは自分で定義した@Autowired注釈をサポートするだけでなく、JSR-250仕様によって定義されたいくつかの注釈をサポートしています。それらはそれぞれ@Resource、@PostConstructおよび@Predestryです。 @Resourceの役割は@Autowiredに相当しますが、@AutowiredはbyTypeで自動注入されます。@ResourceはデフォルトではbyNameで自動注入されます。Resourceには2つの属性が重要で、それぞれnameとtype、Springは@Resourceに注釈されたname属性をbeanの名前に解析し、type属性はbeanのタイプに解析します。したがって、name属性を使用すると、byNameの自動注入ポリシーを使用し、type属性を使用する場合はbyType自動注入ポリシーを使用します。nameもtype属性も指定されていない場合は、反射機構によりbyName自動注入術を使用します。 @Resource組立順序
  • nameとtypeが同時に指定されている場合、Springコンテキストから唯一一致するbeanを見つけて組み立てます。見つけられない場合は例外
  • を投げます。
  • nameが指定されている場合、コンテキストから名前(id)にマッチするbeanを探して組み立て、見つけられない場合は例外
  • を投げます。
  • typeが指定されている場合、タイプマッチングの唯一のbeanを文脈から見つけて組み立てます。見つけられないか、複数が見つからないか、いずれも例外
  • を投げます。
  • nameが指定されておらず、typeが指定されていない場合、自動的にbyName方式で組み立てられます(2をご参照ください)。もし一致していないならば、元のタイプ(UserDao)に戻してマッチングします。マッチングすれば自動的に組み立てられます。
  • 1.6.@PostConstruct(JSR-250) 方法に注釈@PostConstructを加えると、この方法はBean初期化後にSpring容器で実行されます。 典型的な応用シーンの一つは、Beanに父親クラスで定義された属性を注入する必要がありますが、父親タイプの属性や属性のsetterを複写できない場合です。
    public class UserDaoImpl extends HibernateDaoSupport implements UserDao {
    	private SessionFactory mySessionFacotry;
    	@Resource
    	public void setMySessionFacotry(SessionFactory sessionFacotry) {
    		this.mySessionFacotry = sessionFacotry;
    	}
    	@PostConstruct
    	public void injectSessionFactory() {
    		super.setSessionFactory(mySessionFacotry);
    	}
    	...
    }
    
    ここは@PostContstructortを通して、UserDaoImplの父のために定義されたsession Factoryのプライベート属性を注入して、私たちが定義したsession Factory(父の種類のset Session Factory方法はfinalで、複写できない)を入力してからsuper.getsSession Factoryを呼び出すことができます。 1.7.@Predestroy(JSR-250) 方法に注釈@Predestroyを加えると、この方法はBean初期化後にSpring容器で実行されます。私たちはまだそのシーンを使う必要がないので、ここではプレゼンテーションをしません。その使い方は@PostConstructと同じです。 1.8.を使って構成を簡略化する Spring 2.1は注釈駆動、属性ファイルの導入、ロード期間の編入などの機能に便利な構成を提供する新しいcontextのSchema名前空間を追加しています。私たちは注釈自体は何もしないことを知っています。メタデータ情報だけを提供します。メタデータ情報を真に有効にするには、これらのメタデータを処理するプロセッサを動作させなければならない。 AutowiredAnnotationBeanPostProcessorとCommon AnnotationBeanPostProcessorはこれらの注釈のメタデータを扱うプロセッサです。ただし、Springプロファイルで直接定義するのは、これらのBeanが不器用に見える。Springは私達に便利な登録方法を提供してくれました。
    <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-2.5.xsd
    	http://www.springframework.org/schema/context
    	http://www.springframework.org/schema/context/spring-context-2.5.xsd">
    	<context:annotation-config />
    </beans>
    
    <context:annotationfig/>AutowiredAnnotationBeanPostProcessor、Common AnnotationBeabinPostProcessor、Persistence AnnotationPostProcessor、およびRequiredAnted Androcerの4つのベントを暗黙的にSpring容器に登録します。 2.Spring注釈を使ってビーンの定義を完成する 以上では、@Autowiredまたは@Resourceによるビーンへの自動注入を実現する機能を紹介しましたが、どのようにビーンを注釈するかを紹介します。XMLプロファイルからBen定義を完全に除去する構成を紹介します。 2.1.@Component(不推奨使用)、@Repository、@Service、@Controller 対応するクラスに@Component注を加えるだけで、このクラスをビーンと定義します。
    @Component
    public class UserDaoImpl extends HibernateDaoSupport implements UserDao {
    	...
    }
    
    @Component注解で定義されているBeanを使って、デフォルトの名前(id)は小文字の先頭の非限定類名です。ここで定義されているBeanの名前はuserDaoImplです。ビーンの名前を指定することもできます。 @Component(「userDao」) @ComponentはSpringで管理されているすべてのコンポーネントの一般的な形式であり、Springはさらに細かい注釈形式を提供しています。@Repository、@Service、@Controllerはそれぞれ記憶層Ben、業務層Ben、展示層Beanに対応しています。現在のバージョン(2.5)では、これらの注釈は@Componentの意味と同じで、完全に共通しており、Spring以降のバージョンではより多くの意味を追加することがあります。だから、@Repository、@Service、@Controllerを使って@Componentの代わりにすることをオススメします。 2.2.「context:component-scan/」を使ってBean定義の注釈を作業させる
    <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-2.5.xsd
    	http://www.springframework.org/schema/context
    	http://www.springframework.org/schema/context/spring-context-2.5.xsd">
    	<context:component-scan base-package="com.kedacom.ksoa" />
    </beans>
    
    ここでは、全ての要素によって定義されたBeanの構成内容は削除されました。1行の構成を追加するだけで、すべての問題が解決されます。context:component-scan/>のbase-package属性はスキャンが必要な種類のカバンを指定しています。種類のカバンとその再帰的なサブバッグの中のすべての種類は処理されます。 フィルタを定義し、ベースパックのいくつかのクラスを組み入れたり、排除したりすることもできます。Springは以下の4種類のフィルタリング方式をサポートしています。
  • フィルタタイプ表現例説明
  • 注釈org.example.SomeAnnotationは、SomeAnnotationで注釈されたすべてのカテゴリーをフィルタリングします。
  • 類名指定org.example.SomeClassフィルタ指定クラス
  • 正規表現com\.kedacom\.spring\.annotation\.web.*正規表現でクラスをフィルタリングします。
  • AsppectJ表現org.example.*Service+AsppectJ表現によっていくつかのクラスをフィルタリングします。
    正規表現を例にとって、応用例を挙げます。
    	<context:component-scan base-package="com.casheen.spring.annotation">
    		<context:exclude-filter type="regex" expression="com\.casheen\.spring\.annotation\.web\..*" />
    	</context:component-scan>
    
    注目すべきは、構成項目は、注釈駆動Bean定義の機能を実行するためにクラスバッグをスキャンするだけでなく、注釈駆動自動注入の機能も有効にしているので、AutowiredAnnotationPostProcessorとCommon AnnotationBeabint PostProcessorを暗黙的に内部に登録しています。「context:annotationn config/」を削除できます。 2.3.@Scopeを使ってビーンの作用範囲を定義する XMLを使用してビーンを定義する場合、ビーンのscope属性によってビーンの役割範囲を定義する必要があります。私達は同様に@Scope注釈によってこの仕事を完成することができます。
    @Scope("session")
    @Component()
    public class UserSessionBean implements Serializable {
    	...
    }
    
    3.参考 http://kingtai168.iteye.com/blog/244002 http://www.iteye.com/topic/244153 http://static.springframework.org/spring/docs/2.5.x/reference/beans.html#beans-annotationn-config http://static.springframework.org/spring/docs/2.5.x/reference/beans.html#beans-classipath-scanning