【学习笔记】第一个Spring程序-HelloSpring

第一个Spring程序-HelloSpring

使用Spring来写第一个程序,首先要将spring依赖导入,我们这里导入的是 spring-webmvc

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

然后写一个实体类

package com.wang.pojo;
​
public class Hello {
    String str;
​
    public String getStr() {
        return str;
    }
​
    public void setStr(String str) {
        this.str = str;
    }
​
    @Override
    public String toString() {
        return "Hello{" +
                "str='" + str + '\'' +
                '}';
    }
}

注意:一定要写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 id="hello" class="com.wang.pojo.Hello">
       <property name="str" value="helloSpring"/>
   </bean>
</beans>

在配置文件中,一个bean就相当于一个对象,id相当于变量名,class相当于要new的对象

在bean标签中,property是对象的属性,name就是属性名,value是属性值

在第二步中,强调了一定要有set方法,原因就在这里,给属性设值是利用set方法进行注入

第四步,在运行程序中不需要在去new这个实体类对象

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

通过new ClassPathXmlApplicationContext("beans.xml"); 来获取spring的上下文对象

其中的值就是spring配置文件的路径

获得上下文对象后,调用getBean方法获得对象

这个过程就叫做控制反转

控制:谁来控制对象的创建,传统应用程序的对象是由程序本身控制创建的,使用spring后,对象是由spring来创建的

反转:程序本身不创建对象,而变成被动的接受对象

依赖注入:利用set方法来进行注入


 

我们现在利用spring来实现上一篇文章中的案例:

有两个需求:一个是默认用户,一个是spring用户 即两个UserDao实现类

我们在spring配置文件中将这两个类配置进去,用来创建对象

然后将UserServiceImpl配置到文件中,它有一个属性就是UserDao的实现类

<bean id="defaultImpl" class="com.wang.dao.UserDaoImpl"/>
<bean id="springImpl" class="com.wang.dao.UserDaoSpringImpl"/>
​
​
<bean id="UerServiceImpl" class="com.wang.service.UserServiceImpl">
    <property name="userDao" ref="defaultImpl"/>
</bean>

注意:这里property中的属性值是ref因为是对象,value是基本数据类型

public void test03(){
    ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
    UserServiceImpl userServiceImpl = (UserServiceImpl) context.getBean("UserServiceImpl");
​
    userServiceImpl.getUser();
}

 

通过这种方式去创建对象,不需要用户再去直接new UserDao,如果用户要增加或修改需求,可以直接在配置文件中修改UserServiceImpl的属性值即可。

posted @ 2023-02-11 15:38  GrowthRoad  阅读(17)  评论(0编辑  收藏  举报