xwork依賴注入樣本

來源:互聯網
上載者:User

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

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.