用户登录
用户注册

分享至

如何使用struts2中提供的IOC

  • 作者: 菊花朵朵向阳开
  • 来源: 51数据库
  • 2021-08-23

以前只知道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中配置:


        
		/index1.jsp
	


结果:

service1
service2

软件
前端设计
程序设计
Java相关