xwork依赖注入示例

前端之家收集整理的这篇文章主要介绍了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;}}

原文链接:https://www.f2er.com/javaschema/287991.html

猜你在找的设计模式相关文章