编写第一个helloSpring

导包

<dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.3.13</version>
        </dependency>

编写实体类

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 + '\'' +
                '}';
    }
}

注意一定要有set方法,Spring容器需要set方法

编写Spring配置文件

<?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">
    <!--bean这个标签,就相当于new了一个对象。
    我们再也不用去程序中创建对象了,我们可以在xml配置文件中直接创建对象,并且赋值
    用Spring创建对象,这些对象在Spring中都称为bean
    原先创建对象:
    类型 变量名 = new 类型();
    Hello hello = new Hello();
    在bean标签中
    id= 变量名
    class= new 对象
    property = 给对象中的属性值赋值
    -->
    <bean id="hello" class="com.Google.pojo.Hello">
        <property name="name" value="hello,Spring"/>
    </bean>

</beans>

这个配置文件,官网上有,建议去官网拷贝

实现

public class Mytest {

    public static void main(String[] args) {
        //获取Spring的上下文对象
        ApplicationContext context=new ClassPathXmlApplicationContext("Beans.xml");
        //我们的对象都放在Spring中管理了,我们要使用,直接在里面取出来就可以了(ApplicationContext)核心
        Object hello = context.getBean("hello");
        System.out.println(hello.toString());
    }

}

从开始到现在,我们都没有new过对象,因为对象都被Spring容器给托管。 Spring IoC 容器,负责实例化、配置和组装 bean。
运行结果

Hello{name='hello,Spring'}
posted @ 2022-02-07 14:15  小罗要有出息  阅读(18)  评论(0编辑  收藏  举报