Spring 学习笔记

IOC推导

以前:

当我们需要实现链接数据库时,使用

控制翻转IOC

不需要程序员创建对象了,由Spring创建对象

.pojo

package com.pojo;

public class Hello {
    private String name;

    public String getName() {
        return name;
    }

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

    @Override
    public String toString() {
        return "Hello{" +
                "name='" + name + '\'' +
                '}';
    }


}

 

.xml中配置

 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">

<!--    id相当于对象引用,class相当于创建对象-->
<!-- value相当于给变量赋值-->
<bean id="a" class="com.pojo.Hello"> <property name="name" value="Spring"/> </bean> </beans>

Test

import com.pojo.Hello;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Mytest {
    public static void main(String[] args) {
        //获取Spring的上下文对象
        ApplicationContext context=new ClassPathXmlApplicationContext("beans.xml");
        Hello hello= (Hello) context.getBean("a");
        System.out.println(hello.toString());
    }
}

 小结

使用IOC后,不需要创建对象,只需要获取Spring上下文对象,在.xml中配置bean,依赖注入是由set方法实现的。

posted @ 2022-09-15 20:17  萍2樱释  阅读(22)  评论(0)    收藏  举报