「Spring」Bean定義ファイルで DI する
前回、アノテーションを使用して DI する方法について調べた。
http://a4dosanddos.hatenablog.com/entry/2013/07/06/170303
今回は、Bean 定義ファイルを使用して DI する方法について調べたので、その時のメモ。
用意したソースコード、設定ファイルは以下の通り。
ソースコードに関しては、前回のものとほとんど同じです。
変わったのは、次の 3 点。
・@Component、@Autowired の削除
・setter メソッドを追加
・Bean 定義ファイルの内容
■ Hello.java
package hello.no.annotetion.sample; public interface Hello { String hello(); }
■ HelloImpl.java
package hello.no.annotetion.sample; public class HelloImpl implements Hello { private Person person; @Override public String hello() { return "Hello " + person.getName(); } // DI するための setter メソッド public void setPerson(Person person) { this.person = person; } }
■ Person.java
package hello.no.annotetion.sample; public interface Person { String getName(); }
■ PersonImpl.java
package hello.no.annotetion.sample; public class PersonImpl implements Person { @Override public String getName() { return "hoge"; } }
■ HelloServlet2.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"> <!-- HelloImpl に PersonImpl を Autowired で DI する --> <bean id="hello" class="hello.no.annotetion.sample.HelloImpl" autowire="byType" /> <bean id="person" class="hello.no.annotetion.sample.PersonImpl" /> </beans>
上記で HelloServlet.java を /HelloServlet2 といった感じで web.xml でマッピングして
Web ブラウザからアクセスすると「Hello hoge」と表示されるはず。
以上です。
一応今回もドキュメント載せておきます・・・
・Spring Framework Reference Documentation
http://static.springsource.org/spring/docs/3.2.x/spring-framework-reference/html/