Struts2とSpring4でDIを試しているのですが、
下記のコードの場合において、@Autowired
と@Resource
の使い分けが分かりません。
コンポーネントのMyComponent
とサービスのMyMessageService
がありますが、
どちらも@Autowired
を指定しても@Resource
を指定しても動作します。
それぞれどちらを指定するのが正しいのでしょうか。
また、それはなぜでしょうか。
条件によってはどちらかしか使えないとしたら、その条件とは何でしょうか。
環境
- Struts2 (v2.5)
- Spring4 (v4.2.6)
- Tomcat8 (v8.0.26)
- Java8
よろしくお願いします。
以下、ソースコードを貼ります。
FirstAction.java
lang
1package myapp.actions; 2 3import javax.annotation.Resource; 4import myapp.services.*; 5import org.apache.struts2.convention.annotation.*; 6// import org.springframework.beans.factory.annotation.Autowired; 7import com.opensymphony.xwork2.ActionSupport; 8 9public final class FirstAction { 10 11 // @Autowired 12 @Resource 13 MyComponent comp; 14 15 // @Autowired 16 @Resource 17 MyMessageService service; 18 19 @Action(value = "/first", results = { @Result(location = "/index.jsp") }) 20 public String doAction() { 21 System.out.println(comp.calc(3, 5)); 22 System.out.println(service.getMessage()); 23 return ActionSupport.SUCCESS; 24 } 25 26}
MyComponent.java
lang
1package myapp.services; 2 3public interface MyComponent { 4 5 public int calc(int a, int b); 6 7}
MyComponentImp.java
lang
1package myapp.services; 2 3import org.springframework.stereotype.Component; 4 5@Component 6public final class MyComponentImp implements MyComponent { 7 8 @Override 9 public int calc(int a, int b) { 10 return a + b; 11 } 12 13} 14
MyMessageService.java
lang
1package myapp.services; 2 3import org.springframework.stereotype.Service; 4 5@Service 6public final class MyMessageService { 7 8 public String getMessage() { 9 return "MyMessageService.getMessage()"; 10 } 11 12}
applicationContext.xml
lang
1<?xml version="1.0" encoding="UTF-8"?> 2<beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xmlns:context="http://www.springframework.org/schema/context" 5 xsi:schemaLocation=" 6 http://www.springframework.org/schema/beans 7 http://www.springframework.org/schema/beans/spring-beans-4.2.xsd 8 http://www.springframework.org/schema/context 9 http://www.springframework.org/schema/context/spring-context-4.2.xsd"> 10 11 <context:annotation-config /> 12 <context:component-scan base-package="myapp" /> 13 14</beans>
※他のファイルは省略

回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2016/06/07 15:18