Spring Core 控制反转(IoC)容器、依赖注入(DI)综合小案例

案列

本案例适合刚入门spring初学者

假设我们正在构建一个简单的学生管理系统,包括一个Student类,一个StudentDao接口及其实现类StudentDaoImpl,一个StudentService接口及其实现类StudentServiceImpl,以及一个使用StudentService的App类。
文件目录
在这里插入图片描述

准备:首先我我们需要使用maven创建一个基本的web项目,并配置spring对应的坐标
在这里插入图片描述
导入坐标之后记得刷新一下

通过xml配置文件实现

一、定义一个学生类,给出有参构造器和无参构造器
package com.example.pojo;

public class Student {
    private int id;
    private String name;
    public Student(){
    }

    public Student(int id, String name) {
        this.id = id;
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

二、定义一个StudentDao接口
package com.example.dao;

import com.example.pojo.Student;

public interface StudentDao {
    Student getStudentById(int id);
}

三、创建StudentDao接口的实现类StudentDaoImpl
package com.example.dao.impl;

import com.example.dao.StudentDao;
import com.example.pojo.Student;

public class StudentDaoImpl implements StudentDao {
    public Student getStudentById(int id) {
        //假设这个位置拿到数据,实际开发需要操作数据库
        return new Student(1,"张三");
    }
}

四、定义一个StudentService接口
package com.example.service;

public interface StudentService {
	//定义一个方法打印学生信息
    void printStudentInfo(int id);
}
五、创建StudentService接口的实现类StudentServiceImpl
package com.example.service.impl;

import com.example.dao.StudentDao;
import com.example.pojo.Student;
import com.example.service.StudentService;

public class StudentServiceImpl implements StudentService {
    private StudentDao studentDao;

    public StudentServiceImpl(StudentDao studentDao) {
        this.studentDao = studentDao;
    }
    public void printStudentInfo(int id) {
        Student student = studentDao.getStudentById(id);
        System.out.println("学生信息:ID - " + student.getId() + ",姓名 - " + student.getName());
    }
}

六、创建一个Spring配置文件(applicationContext.xml),配置Bean
<?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="studentDao" class="com.example.dao.impl.StudentDaoImpl" />
    <bean id="studentService" class="com.example.service.impl.StudentServiceImpl">
        <constructor-arg ref="studentDao" />
    </bean>
    /**
<!--<bean id="studentService" class="com.example.service.impl.StudentServiceImpl">
这一行告诉Spring IoC容器要创建一个名为studentService的bean,
其类型为com.example.service.impl.StudentServiceImpl。
StudentServiceImpl类是StudentService接口的实现类。-->
<!--<constructor-arg ref="studentDao" />:
这一行表示StudentServiceImpl的构造函数需要一个参数,
该参数是一个对其他bean(studentDao)的引用。
换句话说,这表示StudentServiceImpl依赖于StudentDao类型的对象。当Spring容器创建studentService这个bean时,
它会查找名为studentDao的bean,如果上面没有配置就会对应的bean就会报错,并将其作为参数传递给StudentServiceImpl的构造函数。
这样,StudentServiceImpl的实例就可以使用StudentDao的实例。-->**/
    <bean id="app" class="com.example.App">
        <constructor-arg ref="studentService" />
    </bean>
    /**
<!--    <constructor-arg ref="studentService" />:这一行表示App的构造函数需要一个参数,
该参数是一个对其他bean(studentService)的引用。换句话说,这表示App依赖于StudentService类型的对象。
当Spring容器创建app这个bean时,它会查找名为studentService的bean,并将其作为参数传递给StudentApplication的构造函数。
这样,app的实例就可以使用StudentService的实例。-->**/
</beans>

代码理解

七、创建App类调用StudentService,并编写测试方法
package com.example;

import com.example.service.StudentService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class App {
    private StudentService studentService;

    public App(StudentService studentService) {
        this.studentService = studentService;
    }

    public void run(int id) {
        studentService.printStudentInfo(id);
    }
	//用于测试的main方法
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        App app = (App) context.getBean("app");		//这里的app要和xml中定义的app一致

        app.run(1);
    }
}

最后右键运行程序,输出结果就是我们在dao中设置的对象
在这里插入图片描述

用注解开发实现

一、定义一个Student类,StudentDao接口和上面一样
二、创建StudentDao接口的实现类StudentDaoImpl
package com.example.dao.impl;

import com.example.dao.StudentDao;
import com.example.pojo.Student;
import org.springframework.stereotype.Repository;

@Repository     //表明该类是一个dao层的bean。当Spring框架进行组件扫描时,会自动识别并实例化带有@Repository注解的类
public class StudentDaoImpl implements StudentDao {
    public Student getStudentById(int id) {
        //拿到学生信息
        return new Student(id, "张三");
    }
}

三,定义一个StudentService接口和上面一样
四、创建StudentService接口的实现类StudentServiceImpl
package com.example.service.impl;

import com.example.dao.StudentDao;
import com.example.pojo.Student;
import com.example.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service            //表明该类是一个service层的bean
public class StudentServiceImpl implements StudentService {
    private StudentDao studentDao;

    @Autowired      //自动将匹配的bean注入到下面构造函数,实现dao和service的连接
    public StudentServiceImpl(StudentDao studentDao) {
        this.studentDao = studentDao;
    }
    public void printStudentInfo(int id) {
        Student student = studentDao.getStudentById(id);
        System.out.println("学生信息:ID - " + student.getId() + ",姓名 - " + student.getName());
    }
}
五、创建一个Spring配置类,用于扫描组件
package com.example;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

@Configuration      //标注一个类是一个配置类
@ComponentScan("com.example")       //@ComponentScan用于告诉Spring框架在哪些包中扫描组件。Spring会自动扫描这些包中的类
public class SpringConfig {
//    当你使用@ComponentScan("com.example")注解时,
//    Spring会自动扫描com.example包及其子包下的所有类,
//    并根据这些类上的注解(如@Component、@Service、@Repository等)来创建相应的bean。
//    这样就不需要在SpringConfig配置这些bean了
}
七、创建App类调用StudentService,并编写测试方法
package com.example;

import com.example.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Component;

@Component
public class App {
    private StudentService studentService;
    @Autowired
    public App(StudentService studentService) {
        this.studentService = studentService;
    }

    public void run(int id) {
        studentService.printStudentInfo(id);
    }

    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml111");
        App app = (App) context.getBean("app");

        app.run(10);
    }
}

这次我们把applicationContext.xml配置文件移除还是可以拿到我们配置好的结果

对于我这个小白来说这个小案例还是有点难度的,虽然没用到多少知识点,但毕竟这才第一天学spring,有很多概念还是无法很好理解,只不过好在有一个大体的认识了,不像刚开始那样学得一脸懵!

框架真难学!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yijianace

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值