现在的位置: 首页 > 综合 > 正文

如何使用struts2中提供的IOC

2017年12月07日 ⁄ 综合 ⁄ 共 1139字 ⁄ 字号 评论关闭

以前只知道spring有IOC机制,最近在看struts2的源码发现原来struts2也提供了这个机制,所以就写了个例子测试了下,没想到还真行。这里给出这个例子,至于原理,以后通过源码来分析。

新建一个Action包,在其下建立四个类:

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")

这就是告诉struts2这个属性需要注入,这会在struts2容器中寻找type为UserService,name为service1的对象工厂,通过工厂产生这个对象。

在struts2.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>

结果:

service1
service2

抱歉!评论已关闭.