Spring学习笔记(3)- 注解方式 IOC/DI

1.修改spring-config.xml文件

添加,表示告诉spring要用注解的方式进行配置


  1. 注释掉,该行为在后面将使用注解来完成



    
    
        
    
    
    
        
        
    

3.@Autowired

在Product.java的category属性前加上@Autowired注解


4.测试运行

package com.jd.test;

import com.jd.java.Product;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class testSpring {
    public static void main(String[] args){
        ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
        Product p1 = (Product) context.getBean("p");

        System.out.println(p1.getName());
        System.out.println(p1.getCategory().getName());
    }
}
  1. @Autowired的位置

除了前面的 在属性前加上@Autowired 这种方式外,也可以在setCategory方法前加上@Autowired,这样来达到相同的效果

  1. @Resource

除了@Autowired之外,@Resource也是常用的手段

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

7.对Bean的注解
上述例子是对注入对象行为的注解,那么bean对象本身,比如Category,Product可不可以移出spring-config.xml配置文件,也通过注解进行呢?接下来是如何对Bean进行注解配置
8.修改spring-config.xml文件

新增,其作用是告诉Spring,bean都放在com.jd.java这个包下




      


9.@Component

为Product类加上@Component注解,即表明此类是bean

@Component("p")
public class Product {

为Category 类加上@Component注解,即表明此类是bean

@Component("category")
public class Category {

因为配置从spring-config.xml中移出来了,所以属性初始化放在属性声明上进行了。
private String name="product";
private String name="spring";
Product.java

package com.jd.java;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component("p")
public class Product {

    private int id;
    private String name = "product";

    @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

package com.jd.java;

import org.springframework.stereotype.Component;

@Component("category")
public class Category {
    private int id;
    private String name = "spring";
    public void setName(String name){
        this.name = name;
    }
    public String getName(){
        return name;
    }
    public void setId(int id){
        this.id = id;
    }
    public int getId(){
        return id;
    }
}

10.测试运行

你可能感兴趣的:(Spring学习笔记(3)- 注解方式 IOC/DI)