xwork IOC 注入的使用

Struts2.0中内核中的XWOrk的注入的简单使用。

 

XWork使用Inject注解内核中类:

源代码如下:

 

 

package com.opensymphony.xwork2.inject;

import static com.opensymphony.xwork2.inject.Container.DEFAULT_NAME;

import static java.lang.annotation.ElementType.*;
import java.lang.annotation.Retention;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Target;

/**
 * <p>Annotates members and parameters which should have their value[s]
 * injected.
 *
 * @author [email protected] (Bob Lee)
 */
@Target({METHOD, CONSTRUCTOR, FIELD, PARAMETER})

 //可以看到注解可以在参数,方法,构造函数,字段等上 注解
@Retention(RUNTIME) 
//在运行时执行注解的
public @interface Inject {

  /**
   * Dependency name. Defaults to {@link Container#DEFAULT_NAME}.
   */
  String value() default DEFAULT_NAME;

  /**
   * Whether or not injection is required. Applicable only to methods and
   * fields (not constructors or parameters).
   */
  boolean required() default true;
}

 

 

使用代码如下:

 

 

package cn.com.unutrip.struts2;

public interface IPerson {
 public void say();

}

 

 

package cn.com.unutrip.struts2;

public class Person implements IPerson {

 @Override
 public void say() {
  System.out.println(" xiao bai");
 }

}

 

 

 

package cn.com.unutrip.struts2;

public interface IPersonService {
 public void say();
}

 

 

 

package cn.com.unutrip.struts2;

import com.opensymphony.xwork2.inject.Inject;

public class PersonService implements IPersonService {
 private IPerson person;

 @Override
 public void say() {
  System.out.println(" person service ");
  person.say();

 }

 public IPerson getPerson() {
  return person;
 }

 @Inject
 public void setPerson(IPerson person) {
  this.person = person;
 }

}

 

测试类:

package cn.com.unutrip.struts2;

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

/**
 * xwork IOC 注入的使用
 *
 * @author longgangbai
 *
 */
public class InjectContainer {
 private Container container;

 public static void main(String[] args) {

 //   IOC注入容器


  InjectContainer test = new InjectContainer();
 //容器的创建  

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

}

你可能感兴趣的:(Google,IOC)