微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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;}}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐