Hello,Spring

78 阅读1分钟

刚入门,通过“Hello,Spring”来简单认识一下Spring的使用

  1. 创建一个干净的Maven项目
  2. 导入spring
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.1.10.RELEASE</version>
        </dependency>
    </dependencies>
  1. 建立一个实体类“Hello”,要有set方法
package pojo;

public class Hello {
    private String str;

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

    public String getStr() {
        return str;
    }

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

  1. 创建beans.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
       http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="hello" class="pojo.Hello">
        <property name="str" value="Spring"/>
    </bean>

</beans>

对beans.xml文件的说明

image.png

image.png

补充说明:ref传的是参数类型,value传的是值

  1. 测试类
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import pojo.Hello;

public class DemoTest {
    public static void main(String[] args) {

        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        Hello hello = (Hello) context.getBean("hello");
        System.out.println(hello.toString());
    }
}

  1. 结果:

image.png

  1. 解析一些点:
    • hello对象是由Spring创建的。
    • hellp对象的属性是由Spring容器设置的。