「Spring」アノテーションで DI する
Spring の DI について、ちゃんと使ったことなかったので、勉強してみた。その時のメモ。
DI するには、"アノテーション" 使う方法と、"Bean ファイル" 使う方法があるみたいだけど、
今回は "アノテーション" 使う方法でやってみた。
用意したソースコード、設定ファイルは以下の通り。
@Component、@Autowired あたりが DI する際に必要なアノテーション。
インスタンス変数 ( 以下では person ) の前に @Autowired を付けると、@Component がついた
クラスから、インジェクション可能なクラスを探してきてくれるみたいです。
■ Hello.java
package hello.annotetion.sample; public interface Hello { String hello(); }
■ HelloImpl.java
package hello.annotetion.sample; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class HelloImpl implements Hello { @Autowired private Person person; @Override public String hello() { return "Hello " + person.getName(); } }
■ Person.java
package hello.annotetion.sample; public interface Person { String getName(); }
■ PersonImpl.java
package hello.annotetion.sample; import org.springframework.stereotype.Component; @Component public class PersonImpl implements Person { @Override public String getName() { return "hoge"; } }
■ HelloServlet.java
- 略 - protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ApplicationContext context = (ApplicationContext) getServletContext() .getAttribute( WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE); Hello instatnce = context.getBean(Hello.class); String result = instatnce.hello(); PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<body>"); out.println("<h1>" + result + "</h1>"); out.println("</body>"); out.println("</html>"); } - 略 -
■ 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-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd"> <context:annotation-config /> <context:component-scan base-package="hello.annotetion.sample" /> </beans>
上記で HelloServlet.java を /HelloServlet といった感じで web.xml でマッピングして
Web ブラウザからアクセスすると「Hello hoge」と表示されるはず。
ちょっと自分もまだ Spring の DI についてわかってないので、細かい説明とか書けない感じですが、
とりあえず、以上です。
ちなみにドキュメントは以下ですな。
・Spring Framework Reference Documentation
http://static.springsource.org/spring/docs/3.2.x/spring-framework-reference/html