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