Slideshare.net (beta)

 
Post to TwitterPost to Twitter
Post: 
Myspace Hi5 Friendster Xanga LiveJournal Facebook Blogger Tagged Typepad Freewebs BlackPlanet gigya icons

All comments

Add a comment on Slide 1

If you have a SlideShare account, login to comment; else you can comment as a guest


Showing 1-50 of 0 (more)

Spring Framework勉強会

From matsukaz, 7 months ago

社内で行ったSpring Framework勉強会の資料。<br />Spring Fr more

6653 views  |  1 comment  |  0 favorites  |  48 downloads  |  2 embeds (Stats)
 

Categories

Add Category
 
 

Groups / Events

 

 
Embed
options

More Info

This slideshow is Public
Total Views: 6653
on Slideshare: 6651
from embeds: 2

Slideshow transcript

Slide 1: Spring Framework勉強会 2008/03/04 matsukaz [http://d.hatena.ne.jp/matsukaz/]

Slide 2: 目的 • Spring Frameworkの概念を理解 • Spring Frameworkを使ってみたくなる

Slide 3: アジェンダ • Spring Frameworkの概要 • Spring Framework 2.5の新機能 • まとめ

Slide 4: Spring Frameworkの概要 • Spring Frameworkとは • Spring Frameworkの仕組み • コンテナの起動方法 • インスタンス生成 • インジェクション • スコープ • AOP • トランザクション制御 • etc...

Slide 5: Spring Frameworkの概要 Spring Frameworkとは • Rod Johnson氏の著書「Expert One-on- One J2EE Design and Development」の中 で提案されたIoC(Inversion of Control)パ ターンを実現したフレームワーク • 開発元はSpring Source(元Interface 21) • アプリケーションをPOJOで実装 – SpringのAPIに依存させない • 様々なプロジェクトと連携可能 – 優れたプロジェクトとは競合せずに協調してい く

Slide 6: Spring Frameworkの概要 Spring Frameworkの仕組み • モジュールの種類 出展元 : http://springframework.org/

Slide 7: Spring Frameworkの概要 Spring Frameworkの仕組み • モジュールの種類 モジュール 説明 Core IoCとDIの機能を提供する基本パッケージ Context IoCとDIの機能をフレームワークスタイルで利用可能にする パッケージ DAO JDBC抽象化レイヤの提供やトランザクション管理を行うため のパッケージ ORM JPA、JDO、Hibernate、iBATISなどのO/Rマッピングフレーム ワークとの連携を行うためのパッケージ AOP AOPを利用ためのパッケージ Web Webアプリケーションで利用可能な機能を提供するパッケージ WebWorkやStrutsとの連携時にも利用 MVC Webアプリケーション用のMVCフレームワークを提供するパッ ケージ

Slide 8: Spring Frameworkの概要 コンテナの起動方法 • ClassPathXmlApplicationContext – クラスパスからファイルを読み込んで起動 ApplicationContext ac == ApplicationContext ac new ClassPathXmlApplicationContext(\"applicationContext.xml\"); new ClassPathXmlApplicationContext(\"applicationContext.xml\"); • FileSystemXmlApplicationContext – パス指定でファイルを読み込んで起動 ApplicationContext ac == ApplicationContext ac new FileSystemClassPathXmlApplicationContext(\"conf/appContext.xml\"); new FileSystemClassPathXmlApplicationContext(\"conf/appContext.xml\");

Slide 9: Spring Frameworkの概要 コンテナの起動方法 • XmlWebApplicationContext – WebApp起動時にコンテナも起動 – WebApplicationContextを利用するために ContextLoaderを設定 <listener> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> </listener> または <servlet> <servlet> <servlet-name>context</servlet-name> <servlet-name>context</servlet-name> <servlet-class>org.springframework.web.context.ContextLoaderServlet</servlet-class> <servlet-class>org.springframework.web.context.ContextLoaderServlet</servlet-class> <load-on-startup>1</load-on-startup> <load-on-startup>1</load-on-startup> </servlet> </servlet>

Slide 10: Spring Frameworkの概要 コンテナの起動方法 (続き) – Webスコープを利用するための設定 <listener> <listener> <listener-class> <listener-class> org.springframework.web.context.request.RequestContextListener org.springframework.web.context.request.RequestContextListener </listener-class> </listener-class> </listener> </listener> または <filter> <filter> <filter-name>requestContextFilter</filter-name> <filter-name>requestContextFilter</filter-name> <filter-class>org.springframework.web.filter.RequestContextFilter</filter-class> <filter-class>org.springframework.web.filter.RequestContextFilter</filter-class> </filter> </filter> <filter-mapping> <filter-mapping> <filter-name>requestContextFilter</filter-name> <filter-name>requestContextFilter</filter-name> <url-pattern>/*</url-pattern> <url-pattern>/*</url-pattern> </filter-mapping> </filter-mapping>

Slide 11: Spring Frameworkの概要 コンテナの起動方法 (続き) – 設定ファイルを指定 <context-param> <context-param> <param-name>contextConfigLocation</param-name> <param-name>contextConfigLocation</param-name> <param-value> <param-value> /WEB-INF/applicationContext.xml /WEB-INF/applicationContext.xml </param-value> </param-value> </context-param> </context-param> – WebApplicationContextを取得 ////ApplicationContextの取得に失敗した場合はnullを返す ApplicationContextの取得に失敗した場合はnullを返す ApplicationContext ac ==WebApplicationContextUtils ApplicationContext ac WebApplicationContextUtils .getWebApplicationContext(getServletContext()); //引数はServletContext .getWebApplicationContext(getServletContext()); //引数はServletContext ////ApplicationContextの取得に失敗した場合はIllegalStateExceptionを返す ApplicationContextの取得に失敗した場合はIllegalStateExceptionを返す ApplicationContext ac ==WebApplicationContextUtils ApplicationContext ac WebApplicationContextUtils .getRequiredWebApplicationContext(getServletContext()); .getRequiredWebApplicationContext(getServletContext());

Slide 12: Spring Frameworkの概要 インスタンス生成 • コンストラクタ <bean id=“hoge1\" class=“sample1.HogeImpl\"/> <bean id=“hoge1\" class=“sample1.HogeImpl\"/> • staticファクトリメソッド <bean id=“hoge2\" class=“sample1.HogeImpl\" factory-method=\"createInstance\"/> <bean id=“hoge2\" class=“sample1.HogeImpl\" factory-method=\"createInstance\"/> • インスタンスファクトリメソッド <bean id=\"serviceLocator\" class=“sample1.HogeServiceLocator\"/> <bean id=\"serviceLocator\" class=“sample1.HogeServiceLocator\"/> <bean id=“hoge3\" factory-bean=\"serviceLocator\" factory-method=“createService\"/> <bean id=“hoge3\" factory-bean=\"serviceLocator\" factory-method=“createService\"/>

Slide 13: Spring Frameworkの概要 インジェクション • コンストラクタ・インジェクション public class FugaImpl {{ public class FugaImpl private Hoge hoge; private Hoge hoge; public FugaImpl(Hoge hoge) {{ public FugaImpl(Hoge hoge) this.hoge ==hoge; this.hoge hoge; }} }} <bean name=“fuga1” class=“sample1.FugaImpl”> <bean name=“fuga1” class=“sample1.FugaImpl”> <constructor-arg ref=“hoge1”/> <constructor-arg ref=“hoge1”/> </bean> </bean>

Slide 14: Spring Frameworkの概要 インジェクション • セッター・インジェクション public class FugaImpl {{ public class FugaImpl private Hoge hoge; private Hoge hoge; public void setHoge(Hoge hoge) {{ public void setHoge(Hoge hoge) this.hoge ==hoge; this.hoge hoge; }} }} <bean name=“fuga1” class=“sample1.FugaImpl”> <bean name=“fuga1” class=“sample1.FugaImpl”> <property name=“hoge” ref=“hoge1”/> <property name=“hoge” ref=“hoge1”/> </bean> </bean> p-namespaceを利用すると <bean name=“fuga1” class=“sample1.FugaImpl” p:hoge-ref=“hoge1”/> <bean name=“fuga1” class=“sample1.FugaImpl” p:hoge-ref=“hoge1”/>

Slide 15: Spring Frameworkの概要 インジェクション • Autowiring public class FugaImpl {{ public class FugaImpl private Hoge hoge; private Hoge hoge; public void setHoge(Hoge hoge) {{ public void setHoge(Hoge hoge) this.hoge ==hoge; this.hoge hoge; }} }} – byType(型による指定) <bean name=“fuga1” class=“sample1.FugaImpl” autowire=“byType”/> <bean name=“fuga1” class=“sample1.FugaImpl” autowire=“byType”/> – byName(プロパティ名による指定) <bean name=“fuga1” class=“sample1.FugaImpl” autowire=“byName”/> <bean name=“fuga1” class=“sample1.FugaImpl” autowire=“byName”/>

Slide 16: Spring Frameworkの概要 インジェクション • lookupメソッド・インジェクション public abstract class FooImpl {{ public abstract class FooImpl protected abstract Hoge createHoge(); protected abstract Hoge createHoge(); }} <bean id=\"smpl2.foo1\" class=\"sample2.FooImpl\"> <bean id=\"smpl2.foo1\" class=\"sample2.FooImpl\"> <lookup-method name=\"createHoge\" bean=\"smpl2.hoge2\"/> <lookup-method name=\"createHoge\" bean=\"smpl2.hoge2\"/> </bean> </bean> <bean id=\"smpl2.hoge2\" class=\"sample2.HogeImpl\" scope=\"prototype\"> <bean id=\"smpl2.hoge2\" class=\"sample2.HogeImpl\" scope=\"prototype\"> <property name=\"message\" value=\"Hoge2\"/> <property name=\"message\" value=\"Hoge2\"/> </bean> </bean>

Slide 17: Spring Frameworkの概要 インジェクション • その他の方法 – ServiceLocatorFactoryBean – ObjectFactoryCreatingFactoryBean

Slide 18: Spring Frameworkの概要 インジェクション • Collectionフレームワークをインジェクション – List、Set、Map、Properties public class FooImpl {{ public class FooImpl private List<String> messageList; private List<String> messageList; private Map<Integer, String> users; private Map<Integer, String> users; public void setMessageList(List<String> messageList) {{ public void setMessageList(List<String> messageList) this.messageList ==messageList; this.messageList messageList; }} public void setUsers(Map<Integer, String> users) {{ public void setUsers(Map<Integer, String> users) this.users ==users; this.users users; }} }} <bean name=\"foo1\" class=\"sample3.FooImpl\"> <bean name=\"foo1\" class=\"sample3.FooImpl\"> <property name=\"messageList\"> <property name=\"messageList\"> <list> <list> <property name=\"users\"> <property name=\"users\"> <value>Foo1</value> <value>Foo1</value> <map> <map> <value>Foo2</value> <value>Foo2</value> <entry key=\"1\" value=\"Hoge1\"/> <entry key=\"1\" value=\"Hoge1\"/> </list> </list> </map> </map> </property> </property> </property> </property> </bean> </bean>

Slide 19: Spring Frameworkの概要 スコープ • 用意されているスコープは以下の5つ。 スコープ 説明 singleton コンテナごとにインスタンスは1つ。 prototype 呼ばれるたびにオブジェクトをインスタンス化。 request HTTPリクエスト内でインスタンスは1つ。 実際はrequest.setAttribute(“bean名”, インスタンス)で管理。 session HTTPセッション内でインスタンスは1つ。 実際はsession.setAttribute(“bean名”,インスタンス)で管理。 global PortletベースのWebアプリケーションでのみ利用するスコープ session

Slide 20: Spring Frameworkの概要 スコープ • スコープの異なるBeanをインジェクション – e.g. singletonのBeanにrequestのBeanをイン ジェクションするなど <!-- requestスコープ --> <!-- requestスコープ --> <bean id=\"smpl4.hoge3\" class=\"sample4.HogeImpl\" scope=\"request\"> <bean id=\"smpl4.hoge3\" class=\"sample4.HogeImpl\" scope=\"request\"> <!-- 別のスコープのBeanにインジェクションすることを考慮 --> <!-- 別のスコープのBeanにインジェクションすることを考慮 --> <aop:scoped-proxy/> <aop:scoped-proxy/> <property name=\"message\" value=\"Hoge3\"/> <property name=\"message\" value=\"Hoge3\"/> </bean> </bean> <!-- singletonスコープのBeanにrequestスコープのBeanをインジェクション --> <!-- singletonスコープのBeanにrequestスコープのBeanをインジェクション --> <bean id=\"smpl4.fuga1\" class=\"sample4.FugaImpl\"> <bean id=\"smpl4.fuga1\" class=\"sample4.FugaImpl\"> <property name=\"hoge\" ref=\"smpl4.hoge3\"/> <property name=\"hoge\" ref=\"smpl4.hoge3\"/> </bean> </bean> ※ <aop:scoped-proxy proxy-target-class=“false”/>とすることで、プロキシの 生成方法をCGLIBによるバイトコード生成からJSEのインタフェースベー スのプロキシに変更できる。

Slide 21: Spring Frameworkの概要 AOP • Spring AOPはpure Java – AspectJのように特殊な言語や環境は必要な い • join pointはmethod executionのみサポート • AOPの仕様のフル実装が目的ではない • 定義方法は以下の2つ – @AspectJアノテーション – Bean定義ファイル

Slide 22: Spring Frameworkの概要 AOP • Spring AOPで利用可能なadvice advice 説明 Before advice join pointの前 After returning advice join pointのメソッドが正しく実行された後 After throwing advice join pointのメソッドで例外が発生した後 After advice 結果に関係なくjoin pointの後 Around advice join pointの前後 join pointを呼び出すかどうかを制御可能。

Slide 23: Spring Frameworkの概要 AOP • @Aspectアノテーションを利用した方法 <!-- @Aspectアノテーションを有効化 --> <!-- @Aspectアノテーションを有効化 --> <aop:aspectj-autoproxy/> <aop:aspectj-autoproxy/> <bean id=“smpl5.hogeAspect” class=“sample5.HogeAspect”/> <bean id=“smpl5.hogeAspect” class=“sample5.HogeAspect”/> @Aspect @Aspect public class HogeAspect {{ public class HogeAspect @Pointcut(\"execution(public **sample5.HogeImpl.*(..))\") @Pointcut(\"execution(public sample5.HogeImpl.*(..))\") private void hogeOperation() {} private void hogeOperation() {} @Before(“hogeOperation()”) //pointcutを指定 @Before(“hogeOperation()”) //pointcutを指定 public void beforeAdvice() {{ public void beforeAdvice() }} @AfterReturning(“within(sample5.*)”) //join pointを直接指定 @AfterReturning(“within(sample5.*)”) //join pointを直接指定 public void afterReturingAdvice() {{ public void afterReturingAdvice() }} }}

Slide 24: Spring Frameworkの概要 AOP • Bean定義ファイルを利用した方法 <bean id=“smpl5.hogeAspect” class=“sample5.HogeAspect”/> <bean id=“smpl5.hogeAspect” class=“sample5.HogeAspect”/> <aop:config> <aop:config> <aop:aspect id=\"hogeAspectDef\" ref=\"smpl5.hogeAspect\"> <aop:aspect id=\"hogeAspectDef\" ref=\"smpl5.hogeAspect\"> <!– pointcut定義 --> <!– pointcut定義 --> <aop:pointcut id=\"hogePublicMethod\" <aop:pointcut id=\"hogePublicMethod\" expression=\"execution(public **sample5.HogeImpl.*(..))\"/> expression=\"execution(public sample5.HogeImpl.*(..))\"/> <!-- pointcutを指定 --> <!-- pointcutを指定 --> <aop:before pointcut-ref=\"hogePublicMethod\" method=\"beforeAdvice\"/> <aop:before pointcut-ref=\"hogePublicMethod\" method=\"beforeAdvice\"/> <!-- //join pointとしてwithin()を直接指定 --> <!-- //join pointとしてwithin()を直接指定 --> <aop:after-returning pointcut=\"within(sample5.*)\" method=\"afterReturingAdvice\"/> <aop:after-returning pointcut=\"within(sample5.*)\" method=\"afterReturingAdvice\"/> </aop:aspect> </aop:aspect> </aop:config> </aop:config>

Slide 25: Spring Frameworkの概要 AOP • pointcutの書式 書式 説明 execution メソッド実行 within 型やパッケージを制限する this 指定のインタフェースを実装するProxyオブジェクトに制限する(主にadvice内で 参照する変数宣言のために使用する) target 指定のインタフェースを実装するターゲットオブジェクトに制限する(主にadvice 内で参照する変数宣言のために使用する) args 引数の数と型にマッチするメソッドに制限する(主にadvice内で参照する変数宣 言のために使用する) @target 指定のアノテーションを持つターゲットオブジェクトに制限する @args 引数が指定のアノテーションを含んでいる場合に制限する @within 指定のアノテーションがクラス宣言に含まれているターゲットオブジェクトに制限 する @annotation 指定のアノテーションを含んでいるメソッドに制限する bean Spring管理下のBeanに制限する(※Spring 2.5)

Slide 26: Spring Frameworkの概要 AOP • adviceの順序制御 – 以下のいずれかの方法で制御 • Orderedインタフェースを実装 – int getValue() { return 10; } • @Orderアノテーションを利用 – @Order(value=10) • Bean定義ファイルに記述 – <aop:aspect order=“10”> – 数値の低い方から順番にadviceが適用される

Slide 27: Spring Frameworkの概要 AOP • AOP Proxyの種類 – JSE dynamic proxy [default] • インタフェースを用意する必要がある – CGLIB proxy • バイトコード生成。インタフェースを必要としない • @AspectJアノテーションを利用している場合 – <aop:aspectj-autoproxy proxy-target-class=“true”/> • Bean定義ファイルを利用している場合 <aop:config proxy-target-class=“true”> <aop:config proxy-target-class=“true”> </aop:config> </aop:config>

Slide 28: Spring Frameworkの概要 トランザクション制御 • 同じプログラミングモデルでJTA、JDBC、 Hibernate、JPA、JDOなどのトランザクションAPI を利用可能に。 • 宣言的トランザクション管理をサポート 出展元 : http://springframework.org/

Slide 29: Spring Frameworkの概要 トランザクション制御 • 宣言的トランザクション管理の利用例 package sample; package sample; public interface HogeService {{ public interface HogeService Hoge getHoge(String name); Hoge getHoge(String name); void insertHoge(Hoge hoge); void insertHoge(Hoge hoge); }} public class HogeServiceImpl implements HogeService {{ public class HogeServiceImpl implements HogeService public Hoge getHoge(String name) {{ public Hoge getHoge(String name) ////実装 実装 }} public void insertHoge(Hoge hoge) {{ public void insertHoge(Hoge hoge) ////実装 実装 }} }}

Slide 30: Spring Frameworkの概要 トランザクション制御 • Bean定義ファイルを利用した方法 <bean id=“hogeService” class=“sample.HogeServiceImpl”/> <bean id=“hogeService” class=“sample.HogeServiceImpl”/> <jee:jndi-lookup id=“dataSource” jndi-name=“jdbc/HogeDS”/> <jee:jndi-lookup id=“dataSource” jndi-name=“jdbc/HogeDS”/> <!-- トランザクションマネージャ --> <!-- トランザクションマネージャ --> <bean id=“txManager” class=“org.springframework.jdbc.datasource.DataSourceTransactionManager”> <bean id=“txManager” class=“org.springframework.jdbc.datasource.DataSourceTransactionManager”> <property name=“dataSource” ref=“dataSource”/> <property name=“dataSource” ref=“dataSource”/> </bean> </bean> <!– トランザクションの適用方法をadviceとして定義 --> <!– トランザクションの適用方法をadviceとして定義 --> <tx:advice id=“txAdvice” transaction-manager=“txManager”> <tx:advice id=“txAdvice” transaction-manager=“txManager”> <tx:attributes> <tx:attributes> <tx:method name=“get*” read-only=“true”/> <tx:method name=“get*” read-only=“true”/> <tx:method name=“*” propagation=“REQUIRED” rollback-for=“sample.HogeException”/> <tx:method name=“*” propagation=“REQUIRED” rollback-for=“sample.HogeException”/> <tx:attributes> <tx:attributes> </tx:advice> </tx:advice> <!– トランザクション管理対象をpointcutで指定 --> <!– トランザクション管理対象をpointcutで指定 --> <aop:config> <aop:config> <aop:pointcut id=“hogeServiceOperation” expression=“execution(* sample.HogeServiceImpl.*(..))”/> <aop:pointcut id=“hogeServiceOperation” expression=“execution(* sample.HogeServiceImpl.*(..))”/> <aop:advisor advice-ref=“txAdvice” pointcut-ref=“hogeServiceOperation”/> <aop:advisor advice-ref=“txAdvice” pointcut-ref=“hogeServiceOperation”/> </aop:config> </aop:config>

Slide 31: Spring Frameworkの概要 トランザクション制御 • <tx:method/>の属性一覧 属性 必須 デフォルト 説明 name Yes トランザクション制御の適用対象をメソッド名で指定。ワイ ルドカード(*)を利用可能 ‘get*’、’on*Event’など。 propagation No REQUIRED トランザクションの振る舞いを指定。REQUIRED、 SUPPORTS、MANDATORY、REQUIRES_NEW、 NOT_SUPPORTED、NEVER、NESTEDから指定。 isolation No DEFAULT トランザクションの分離レベルを指定。DEFAULT、 READ_UNCOMMITTED、READ_COMMITTED、 REPEATABLE_READ、SERIALIZABLEから指定。 timeout No -1 トランザクションのタイムアウト時間を秒指定。 read-only No false トランザクションを読み取り専用とするか否か。 rollback-for No ロールバックを行うExceptionをカンマ区切りで指定。 Exception系の例外は、そのままではロールバックされな いため、ロールバックを行いたい場合などに指定。 no-rollback-for No ロールバックを行わないExceptionをカンマ区切りで指定。 RuntimeException系の例外は、そのままではロールバック されるため、ロールバックさせたくない場合などに指定。

Slide 32: Spring Frameworkの概要 トランザクション制御 • @Transactionalを利用した方法 @Transactional @Transactional public class HogeServiceImpl {{ public class HogeServiceImpl @Transactional(readOnly=true) @Transactional(readOnly=true) public Hoge getHoge(String name) {{ public Hoge getHoge(String name) ////実装 実装 }} @Transactional( @Transactional( propagation=Propagation.REQUIRED, propagation=Propagation.REQUIRED, rollbackFor=sample.HogeException) rollbackFor=sample.HogeException) public void insertHoge(Hoge hoge) {{ public void insertHoge(Hoge hoge) ////実装 実装 }} }} <tx:annotation-driven transaction-manager=“txManager”/> <tx:annotation-driven transaction-manager=“txManager”/>

Slide 33: Spring Frameworkの概要 トランザクション制御 • @Transactionalのプロパティ プロパティ 型 説明 propagation enum:Propagation トランザクションの振る舞いを指定。値はBean定義ファイル の<tx:method/>の場合と同様。 isolation enum:Isolation トランザクションの分離レベルを指定。値はBean定義ファイ ルの<tx:method/>の場合と同様。 timeout int トランザクションのタイムアウト時間を秒指定。 readOnly boolean トランザクションを読み取り専用とするか否か。 rollbackFor Classオブジェクトの ロールバックを行う例外クラスを配列で指定。 配列 rollbackForClas クラス名の配列 ロールバックを行う例外クラス名を配列で指定。 sname noRollbackFor Classオブジェクトの ロールバックを行わない例外クラスを配列で指定。 配列 noRollbackForC クラス名の配列 ロールバックを行わない例外クラス名を配列で指定。 lassname

Slide 34: Spring Frameworkの概要 etc... • Bean定義の継承 <bean id=\"smpl6.fugaAbstract\" class=\"sample6.FugaImpl\" abstract=\"true\"> <bean id=\"smpl6.fugaAbstract\" class=\"sample6.FugaImpl\" abstract=\"true\"> <property name=\"hoge\" ref=\"smpl6.hoge1\"/> <property name=\"hoge\" ref=\"smpl6.hoge1\"/> </bean> </bean> <bean id=\"smpl6.fuga1\" parent=\"smpl6.fugaAbstract\"> <bean id=\"smpl6.fuga1\" parent=\"smpl6.fugaAbstract\"> <property name=\"message\" value=\"Fuga1\"/> <property name=\"message\" value=\"Fuga1\"/> </bean> </bean>

Slide 35: Spring Frameworkの概要 etc... • コールバック・メソッド – Beanのインスタンス化や破棄を行った際の コールバックを受け付けるメソッドを設定可能。 – 設定方法 • InitializingBean/DisposableBeanインタフェースを 実装 • Bean定義ファイルにinit-method/destroy- method属性を指定 • アノテーションで指定(Spring 2.5の新機能で説明)

Slide 36: Spring Frameworkの概要 etc... • lazy-init – singletonスコープのBeanは、デフォルトでは 起動時に全てインスタンス化される。 lazy-initをtrueに設定することで、必要になっ たときにインスタンス化するように、インスタン ス化のタイミングを遅らせることができる。 • テスト時などに有効。

Slide 37: Spring Frameworkの概要 etc... • XMLスキーマを利用した設定 スキーマ 説明 util ユーティリティ機能を提供 jee JNDI/EJBのlookupの設定 lang 動的言語の設定 jms JMSの設定 tx トランザクションの設定 aop AOPの設定 context ApplicationContextの設定

Slide 38: Spring Frameworkの概要 etc... • PropertyPlaceholderConfigurer – プロパティファイルを読み込み、Bean定義ファ イル中の置換文字列として利用可能にする <bean class=\"org.springframework.beans.factory.config.PropertyPlaceholderConfigurer\"> <bean class=\"org.springframework.beans.factory.config.PropertyPlaceholderConfigurer\"> <property name=\"locations\"> <property name=\"locations\"> <value>classpath:com/foo/jdbc.properties</value> <value>classpath:com/foo/jdbc.properties</value> </property> </property> </bean> </bean> <bean id=\"smpl6.hoge1\" class=\"sample7.HogeImpl\" scope=\"prototype\"> <bean id=\"smpl6.hoge1\" class=\"sample7.HogeImpl\" scope=\"prototype\"> <property name=\"message\" value=“${sample7.hoge}\"/> <property name=\"message\" value=“${sample7.hoge}\"/> </bean> </bean> – <context:property-placeholder/>で代替可能 <context:property-placeholder location=\"classpath:sample7/system.properties\"/> <context:property-placeholder location=\"classpath:sample7/system.properties\"/>

Slide 39: Spring Frameworkの概要 etc... • ResourceBundleMessageSource – ResouceBundleを利用し、MessageSourceをイ ンスタンス化する <bean id=\"messageSource“ <bean id=\"messageSource“ class=\"org.springframework.context.support.ResourceBundleMessageSource\"> class=\"org.springframework.context.support.ResourceBundleMessageSource\"> <property name=\"basename\" value=\"sample7/messages\"/> <property name=\"basename\" value=\"sample7/messages\"/> </bean> </bean> MessageSource messages ==(MessageSource) ac.getBean(\"messageSource\"); MessageSource messages (MessageSource) ac.getBean(\"messageSource\"); System.out.println(messages.getMessage(\"sample7.hoge\", new Object[]{\"Hoge1\"}, null)); System.out.println(messages.getMessage(\"sample7.hoge\", new Object[]{\"Hoge1\"}, null));

Slide 40: Spring Framework2.5の新機能 • アノテーションによるインジェクション • アノテーションによるBean定義 • アノテーションによるライフサイクルメソッド • アノテーションを有効にする方法

Slide 41: Spring Framework2.5の新機能 アノテーションによるインジェクション • @Autowired、@Qualifier – メソッドまたはフィールドに付与することで、 Beanが自動的にインジェクションされる • フィールド – privateでもOK • メソッド – setter以外でもOK public class FugaImpl implements Fuga {{ public class FugaImpl implements Fuga @Autowired @Autowired @Qualifier(“hoge”) //@Qualifier省略時はbyType、指定するとbyName @Qualifier(“hoge”) //@Qualifier省略時はbyType、指定するとbyName private Hoge hoge; private Hoge hoge; }}

Slide 42: Spring Framework2.5の新機能 アノテーションによるインジェクション • @Resource – @Autowired + @Qualifier – Bean名の他、JNDIの指定も可能 – JSR-250(Common Annotations for the Java Platform)のアノテーション public class FugaImpl implements Fuga {{ public class FugaImpl implements Fuga @Resource(name=“hoge”) @Resource(name=“hoge”) private Hoge hoge; private Hoge hoge; }}

Slide 43: Spring Framework2.5の新機能 アノテーションによるインジェクション • @Required – Beanを必ずインジェクションさせたい場合に指 定 • フィールドには設定できない。メソッドのみ。 – @Resourceと一緒に利用 – @Autowiredにはrequired属性があり、デフォ ルトでtrueになっている。 public class FugaImpl implements Fuga {{ public class FugaImpl implements Fuga private Hoge hoge; private Hoge hoge; @Required @Required @Resource(name=“hoge”) @Resource(name=“hoge”) public void setHoge(Hoge hoge) {{ public void setHoge(Hoge hoge) this.hoge ==hoge; this.hoge hoge; }} }}

Slide 44: Spring Framework2.5の新機能 アノテーションによるBean定義 • @Component – Beanとして登録したいクラスに指定する – 引数にBean名を指定する • 省略時はクラス名の先頭を小文字にした名前で Bean登録される。 @Component(“fuga”) @Component(“fuga”) public class FugaImpl implements Fuga {{ public class FugaImpl implements Fuga @Autowired @Autowired @Qualifier(“hoge”) @Qualifier(“hoge”) private Hoge hoge; private Hoge hoge; }}

Slide 45: Spring Framework2.5の新機能 アノテーションによるBean定義 • @Repository – @Componentの拡張アノテーション – Persistence層のBeanに適用する – DAOで発生した例外をDataAccessException に変換 • 例外ハンドリングを容易にする • DAO実装に依存しない @Repository(“fugaDAO”) @Repository(“fugaDAO”) public class FugaDAOImpl implements FugaDAO {{ public class FugaDAOImpl implements FugaDAO }}

Slide 46: Spring Framework2.5の新機能 アノテーションによるBean定義 • @Service – @Componentの拡張アノテーション – Service層のBeanに適用 – ただし、現状では@Componentとの違いはな い – 今後機能を付与していく予定 @Service(“fugaDAO”) @Service(“fugaDAO”) public class FooServiceImpl implements FooService {{ public class FooServiceImpl implements FooService }}

Slide 47: Spring Framework2.5の新機能 アノテーションによるBean定義 • @Controller – @Componentの拡張アノテーション – Spring Web MVCフレームワークで、Controller の役割を果たすBeanに適用

Slide 48: Spring Framework2.5の新機能 アノテーションによるBean定義 • @Scope – Beanのスコープを設定する – Bean定義ファイルと同様の指定が可能 – scoped-proxyはBean定義ファイルで行う @Component(\"hoge\") @Component(\"hoge\") @Scope(\"prototype\") @Scope(\"prototype\") public class HogeImpl implements Hoge {{ public class HogeImpl implements Hoge }}

Slide 49: Spring Framework2.5の新機能 アノテーションによるライフサイクルメソッド • @PostConstruct、@PreDestroy – Bean生成時や破棄のタイミングで実行される コールバックメソッドに指定 – JSR-250のアノテーション public class HogeImpl implements Hoge {{ public class HogeImpl implements Hoge @PostConstruct @PostConstruct public void init() {{ public void init() }} @PreDestroy @PreDestroy public void destroy() {{ public void destroy() }} }}

Slide 50: Spring Framework2.5の新機能 アノテーションによるライフサイクルメソッド • ライフサイクルメソッドの実行順 – Bean生成時 • @PostConstructアノテーションを適用したメソッド • InitializingBeanインタフェースの afterPropertiesSet() • Bean定義ファイルでinit-methodで指定したメソッド – Bean破棄時 • @PreDestroyアノテーションを適用したメソッド • DisposableBeanインタフェースのdestroy() • Bean定義ファイルでdestroy-methodで指定したメ ソッド

Slide 51: Spring Framework2.5の新機能 アノテーションを有効にする方法 • @Autowired、@Resourceを利用 <context:annotation-config/> <context:annotation-config/> • @Component、@Repository、@Serviceなど を利用 <context:component-scan base-package=“sample8”/> <context:component-scan base-package=“sample8”/> – base-package配下のアノテーションを全て検 知 – component-scanを指定した場合は、 annotation-configは指定しなくても良い

Slide 52: Spring Framework2.5の新機能 アノテーションを有効にする方法 • component-scanをカスタマイズする – include-filterとexclude-filterにより、コンポー ネントの検出対象を制御可能 • テスト時など、一時的にBeanを切り替える場合な どに有効 <context:component-scan base-package=“sample8”> <context:component-scan base-package=“sample8”> <context:exclude-filter type=“assignable” expression=“sample8.HogeImpl”/> <context:exclude-filter type=“assignable” expression=“sample8.HogeImpl”/> </context:component-scan> </context:component-scan> type属性 例 annotation org.example.SomeAnnotation assignable org.example.SomeClass regex org¥.example¥.Default.* aspectj org.example..*Service+

Slide 53: まとめ • Spring 2.5のアノテーションを利用すれば XML地獄から解放される。 – 全てアノテーションで書くことが正しいかは別。 • 個人的にはログ出力や例外ハンドリングはアノ テーション、トランザクション制御はXMLが好み。 • 基本的にPOJOなので分業化が図りやす い。 • Spring単体では大したことはできない。 – 外部プロジェクトと連携して威力が発揮される。 • 統一の取れたプログラミングモデル。