Spring学习笔记(三):注解方式IOC/DI

学习资料:http://how2j.cn/k/spring/spring-annotation-ioc-di/1067.html

这一节讲的是,如何用注解的方式实现注入对象中同样的效果
注解使用的关键词为

@Autowired

修改XML的内容为

    <context:annotation-config/>
    <bean name="c" class="com.how2java.pojo.Category">
        <property name="name" value="category 1" />
    </bean>
    <bean name="p" class="com.how2java.pojo.Product">
        <property name="name" value="product1" />
<!--         <property name="category" ref="c" /> -->
    </bean>

在<bean>之前添加<context:anootation-config/> 即通知Spring以注解的方式进行配置
并且注释掉"p"的bean中对"c"的引用
取而代之的,修改Product.java,在定义category属性前加上@Autowired(也可以写在category的setter方法前)

package com.how2java.pojo;
import org.springframework.beans.factory.annotation.Autowired;
public class Product {
 
    private int id;
    private String name;
    @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;
    }
}

之后,运行上一节中同样的测试用例TestSpring便可以得到相同的结果

能实现同样效果的注释还有

@Resource(name="c")
private Category category;

以上是对 注入对象 这个行为进行注解配置

==================================================================================================

以下是对 Bean 进行注解配置
修改xml,把<bean>的内容删除,之前的<context:anootation-config/>修改为

<context:component-scan base-package="com.how2java.pojo"/>

这样<bean>的内容就不用写在xml中,Spring会在"com.how2java.pojo"这个目录中根据注解找到bean
因此,现在要为分别修改Category.java和Product.java,添加注解标识:在其类声明之前注解@Component(id)
这里id的作用即与之前的关键字"p"、"c"相同
同时类中属性的初始化也直接写在属性声明上,如private String name="product 1"
因为,修改完后的Product.java如下

package com.how2java.pojo;
 
import javax.annotation.Resource;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
 
@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.java与此类似
再运行TestSpring测试,可以得到相同结果,且此时xml的配置变得非常简洁。

猜你喜欢

转载自blog.csdn.net/HiflyMaple/article/details/87065788