Spring的简单的依赖注入

版权声明:原创文章,未经允许不得转载 https://blog.csdn.net/Destiny_strive/article/details/82529411

Spring的核心思想是IOC和AOP

IOC(Inversion Of Control )反转控制 是Spring的基础,就是创建对象由以前的编程人员new 构造方法来调用,变成了交由Spring创建对象 。

实现IOC需要DI做支持。

DI(Dependency Inject) 依赖注入  ,就是拿到的对象的属性,已经被注入好相关值了,直接使用即可。 

maven中添加依赖

1.首先创建好一个pojo的属性和get、set方法

public class Student {
    private int id;;
    private String name;
    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;
    }
    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}

2.在spring配置文件中添加需要管理的对象

3.测试,输出student对象的name属性的值

spring根据构造函数注入:

给Sutdent类添加一个有参的构造方法,并且把无参的构造方法加上 

修改spring配置文件后再次测试student对象的name的值

注入对象:

创建好school对象,school对象中有id,name属性,生成get,set方法,把school对象添加到spring中管理

方式1:引用school。

修改student类,添加:

测试

方式二:注解方式

在spring配置文件中,开启注解 <context:annotation-config/>

把刚才student引用的school注释掉,在student类的school属性上添加注解@Autowired或@Resource(name = "school")

//@Resource(name = "school")
@Autowired
private School school;

public School getSchool() {
    return school;
}
public void setSchool(School school) {
    this.school = school;
}

再次测试结果一样。

猜你喜欢

转载自blog.csdn.net/Destiny_strive/article/details/82529411
今日推荐