どのようにstruts 2で提供されたIOCを使いますか?

2032 ワード

以前はspringだけ知っていましたが、最近はstruts 2のソースコードを見ていますが、もともとstruts 2もこのメカニズムを提供していましたので、例を書いてテストしました.ここでこの例を示します.原理については、後からソースコードで分析します.
新しいアクションバッグを作って、その下に四つのクラスを作ります.
package Action;

public interface UserService {
	public void test();
}
 
package Action;

public class Service1 implements UserService{

	public void test() {
		// TODO Auto-generated method stub
		System.out.println("service1");
	}
	
	
}
 
package Action;

public class Service2 implements UserService{

	public void test() {
		// TODO Auto-generated method stub
		System.out.println("service2");
	}

}
 
これは次のactionです.
public class injectionAction extends ActionSupport {
	
	@Inject(value="service1")
	private UserService service1;
	
	public String execute() throws Exception {
		
		service1.test();
		
		UserService service2=ActionContext.getContext().getContainer().
		    getInstance(UserService.class, "service2");
		service2.test();
        return SUCCESS;
    }
}
 
注意
@Inject(value="service1")
これはstruts 2にこの属性を注入する必要があるということを教えています.これはstruts 2容器の中でtypeをUserServiceとして探しています.nameはservice 1の対象工場です.工場を通じてこの対象を作ります.struts 2.xmlに設定します.
<bean type="Action.UserService" name="service1" class="Action.Service1"></bean>
<bean type="Action.UserService" name="service2" class="Action.Service2"></bean>
<action name="service" class="Action.injectionAction">
        <result>
		/index1.jsp
	</result>
</action>
結果:
service 1 service 2