首页 > 编程语言 > 详细

Spring5 第一个程序

时间:2021-01-05 14:59:45      阅读:17      评论:0      收藏:0      [点我收藏+]

Spring5 第一个程序

1.导入pom依赖:

<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.2.0.RELEASE</version>
</dependency>

3.新建一个pojo类:

技术分享图片

package com.xiaofu.pojo;

public class Hello {
    private String str;

    public String getStr() {
        return str;
    }

    public void setStr(String str) {
        this.str = str;
    }

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

2.编写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">

    <!--使用spring来创建对象,在spring这些都称为bean-->
    <!--一个bean就相当于一个对象-->
    <!--property 相当于给属性设置值 name 类的属性名 value 给属性设置的值-->
    <bean id="hello" class="com.xiaofu.pojo.Hello">
        <property name="str" value="Spring"/>
    </bean>
</beans>

现在刚刚创建的类 就已经被spring管理了

3.使用容器来使用对象:

技术分享图片

 新建一个测试类来使用一下spring的容器:
代码:

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

public class Text {
    public static void main(String[] args) {
        //获取spring的上下文对象
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        //我们的对象现在都在spring容器中管理了,我们要使用,直接去里面取出来就可以了!
        Hello hello = (Hello) context.getBean("hello"); //这的hello 对应的就是beans.xml文件中的bean标签的id
        System.out.println(hello.toString());
    }
}

运行一下:
技术分享图片

 可以看到 并没有 new一个Hello对象 我们设置和拿到的类的属性

 

Spring5 第一个程序

原文:https://www.cnblogs.com/love2000/p/14235012.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!