Spring初步使用

注入对象

沿用上次的工程
新建两个类
Category和Product

Category.java

public class Category {

  public int getId() {
    return id;
  }
  public void setId(int id) {
    this.id = id;
  }
  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }
  private int id;
  private String name="category 1";
}

Product.java

public class Product {
  private int id;
  private String name="product 1";

  private Category category;

  public int getId() {
    return id;
  }

  public void setId(int id) {
    this.id = id;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public Category getCategory() {
    return category;
  }

  public void setCategory(Category category) {
    this.category = category;
  }
}

修改spring-config.xml

   <bean name="c" class="com.isdust.zor.pojo.Category">
        <property name="name" value="category 1"/>
    </bean>
    <bean name="p" class="com.isdust.zor.pojo.Product">
        <property name="name" value="product1" />
        <property name="category" ref="c"/>
    </bean>

其中ref用来标记注入,将product注入到category中
执行结果如下:
clipboard.png

采用注解方式注入对象

修改product和category,加入注解,并赋予默认值

//为Product类加上@Component注解,即表明此类是bean
@Component("p")
public class Product {
  private int id;
  private String name="product 1";

  @Autowired
  private Category category;

  public int getId() {
    return id;
  }

  public void setId(int id) {
    this.id = id;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public Category getCategory() {
    return category;
  }

  public void setCategory(Category category) {
    this.category = category;
  }
}

//为Category 类加上@Component注解,即表明此类是bean
@Component("c")
public class Category {

  public int getId() {
    return id;
  }
  public void setId(int id) {
    this.id = id;
  }
  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }
  private int id;
  private String name="category 1";
}

修改spring-config.xml,删除所有子标签,加入自动扫描

<context:component-scan base-package="com.isdust.zor.pojo"/>
<context:annotation-config/>

执行结果

clipboard.png

结果同xml指定相同

致谢
参考资料
官方文档
http://how2j.cn/k/spring/spri...


zorpan
41 声望14 粉丝

记笔记