如何使用struts2中提供的IOC

本文介绍了一个使用 Struts2 的 IOC 机制的例子。通过创建 UserService 接口及其实现类 Service1 和 Service2,展示了如何在 Action 类中注入依赖,并在 struts2.xml 中进行配置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

以前只知道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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值