@Autowiredと@ServiceでDependency Injection


スポンサーリンク

依存性を見つけるためには、クラスは@Serviceアノテーションを付与する必要があります。
Serviceアノテーションは、そのクラスがサービスであることを示します。
加えて、設定ファイルにcomponent-scanエレメントを追加します。

サンプルを示します。
ディレクトリ構成は以下のとおりです。



この記事に載っていないコードは、前の記事などにありますので、タグ「Spring Framework」内の記事を検索していただければと思います。

以下のように、プロパティに@Autowiredを付与することで、FriendServiceのインスタンスがインジェクションされます。

	@Autowired
	private FriendService friendService;

@Autowiredを使っているコントローラ全体のソースは以下のようになっています。

FriendController.java

package sample2.controller;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import sample1.domain.Friend;
import sample1.form.FriendForm;
import sample2.service.FriendService;

@Controller
public class FriendController {
	private static final Log logger = LogFactory.getLog(FriendController.class);
	
	@Autowired
	private FriendService friendService;
	
	@RequestMapping(value="/friend_input")
	public String inputFriend() {
		logger.info("inputFriend called");
		return "/jsp/FriendForm";
	}
	
	@RequestMapping(value="/friend_save", method = RequestMethod.POST)
	public String saveFriend(FriendForm friendForm, RedirectAttributes redirectAttributes) {
		logger.info("saveFriend called");
		
		Friend friend = new Friend();
		friend.setName(friendForm.getName());
		friend.setAge(friendForm.getAge());
		friend.setInterest(friendForm.getInterest());
		
		Friend savedFriend = friendService.add(friend);
		
		redirectAttributes.addFlashAttribute("message", "友人情報が保存されました。");
		return "redirect:/friend_view/" + savedFriend.getId();
	}
	
	@RequestMapping(value = "/friend_view/{id}")
	public String viewFriend(@PathVariable Long id, Model model) {
		Friend friend = friendService.get(id);
		model.addAttribute("friend", friend);
		return "/jsp/FriendView";
	}
	
}

インジェクションされる側のクラスには@Serviceというアノテーションを付与します。

FriendServiceImpl.java

package sample2.service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;

import org.springframework.stereotype.Service;

import sample1.domain.Friend;

@Service
public class FriendServiceImpl implements FriendService{

	private Map<Long, Friend> friends = new HashMap<Long, Friend>();
	private AtomicLong generator = new AtomicLong();
	
	public FriendServiceImpl() {
		Friend friend = new Friend();
		friend.setName("madoka");
		friend.setAge("28");
		friend.setInterest("cooking");
	}

	public Friend add(Friend friend) {
		long newId = generator.incrementAndGet();
		friend.setId(newId);
		friends.put(newId, friend);
		return friend;
	}

	public Friend get(long id) {
		return friends.get(id);
	}
	

	
}

FriendService.java

package sample2.service;

import sample1.domain.Friend;

public interface FriendService {
	Friend add(Friend friend);
	Friend get(long id);
}

web.xml

<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
         id="WebApp_ID" version="2.5">

    <display-name>spring-web</display-name>
    
    <filter>
    <filter-name>Encoding</filter-name>
    <filter-class>filter.EncodingFilter</filter-class>
    <init-param>
        <param-name>encoding</param-name>
        <param-value>utf-8</param-value>
    </init-param>
	</filter>
	<filter-mapping>
    	<filter-name>Encoding</filter-name>
    	<url-pattern>/*</url-pattern>
	</filter-mapping>
    
   <!--
		- Location of the XML file that defines the root application context.
		- Applied by ContextLoaderListener.
	-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring/application-config.xml</param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    
    
    <!--
		- Servlet that dispatches request to registered handlers (Controller implementations).
	-->
    <servlet>
        <servlet-name>spring-web</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/mvc-config.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>

    </servlet>

    <servlet-mapping>
        <servlet-name>spring-web</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>


mvc-config.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:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
		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">

    <!-- Uncomment and your base-package here:
         <context:component-scan
            base-package="org.springframework.samples.web"/>  -->

	<context:component-scan base-package="sample2.controller"/>
	<context:component-scan base-package="sample2.service" />
	
    <mvc:annotation-driven />

<!--  
	<bean name="/friend_input.action"
		class="sample1.controller.InputFriendController" />
		
	<bean name="/friend_save.action"
		class="sample1.controller.SaveFriendController" />
-->		
	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
	        <!-- Example: a logical view name of 'showMessage' is mapped to '/WEB-INF/jsp/showMessage.jsp' -->
	        <property name="prefix" value="/WEB-INF/view" />
	        <property name="suffix" value=".jsp"/>
	</bean>
	

</beans>


<参考>

Spring MVC: A Tutorial

Spring MVC: A Tutorial

Spring Framework 4プログラミング入門

Spring Framework 4プログラミング入門

Spring Framework

Spring Framework