xwork依赖注入示例

package xworktest;
/**
* @author wangmingjie
* @date 2008-9-13上午11:13:38
*/
public interface IPerson {
public void say();
}

====================================

package xworktest;
/**
* @author wangmingjie
* @date 2008-9-13上午11:14:33
*/
public class Person implements IPerson {

public void say() {
System.out.println("这是:person");
}

}

====================================

package xworktest;
/**
* @author wangmingjie
* @date 2008-9-13上午11:14:00
*/
public interface IPersonService {
public void say();
}

====================================

package xworktest;

import com.opensymphony.xwork2.inject.Inject;

/**
* @author wangmingjie
* @date 2008-9-13上午11:15:25
*/
public class PersonService implements IPersonService {
private IPerson person;

public IPerson getPerson() {
return person;
}

/**
* 这个注释就是说明需要依赖注入
* @param person
*/
@Inject
public void setPerson(IPerson person) {
this.person = person;
}

public void say() {
System.out.println("userperson");
person.say();
}

}
====================================

package xworktest;

import com.opensymphony.xwork2.inject.Container;
import com.opensymphony.xwork2.inject.ContainerBuilder;

/**
* 测试xwork的inject注解的使用。了解xwork的Container容器。
* 在xwork中的container使用了动态代理技术。
* @author wangmingjie
* @date 2008-9-13上午11:17:35
*/
public class ContainerTest {
private Container container;

public static void main(String[] args) {
ContainerTest test = new Containertest();
ContainerBuilder cb = new ContainerBuilder();
cb=cb.factory(IPerson.class,Person.class);
cb=cb.factory(IPersonService.class,PersonService.class);
test.setContainer(cb.create(true));
// 注释掉的代码也是正确的
//test.setContainer(new ContainerBuilder().factory(IPerson.class,
//Person.class).factory(IPersonService.class,PersonService.class)
//.create(true));

Container container = test.getContainer();

IPersonService person = container.getInstance(IPersonService.class);
person.say();

}

public Container getContainer() {
return container;
}

public void setContainer(Container container) {this.container = container;}}

相关文章

迭代器模式(Iterator)迭代器模式(Iterator)[Cursor]意图...
高性能IO模型浅析服务器端编程经常需要构造高性能的IO模型,...
策略模式(Strategy)策略模式(Strategy)[Policy]意图:定...
访问者模式(Visitor)访问者模式(Visitor)意图:表示一个...
命令模式(Command)命令模式(Command)[Action/Transactio...
生成器模式(Builder)生成器模式(Builder)意图:将一个对...