Spring IoC & DI 超详细解析

前言❤️❤️

hello hello💕,这里是洋不写bug~😄,欢迎大家点赞👍👍,关注😍😍,收藏🌹🌹

IoC是Spring的两大核心思想之一(另一个是AOP,后续博客中会解析)

IoC(Inversion of Controll)的翻译就是控制反转,指的就是Bean的控制权发生了反转,正常是谁使用对象,谁控制对象,现在是由Spring来控制这个对象的创建、销毁,也就是管理这个对象的生命周期

这部分的知识并不难,但是练习时要来回改代码,代码量还是比较大的,这篇博客会先从IoC思想开始解析,用前面博客完成小部分的图书管理系统项目作为入门案例,来详细的解析IoC和DI🐵

🎆个人主页:洋不写bug的博客
🎆所属专栏:JavaEE进阶专栏
🎆铁汁们对于JavaEE进阶的各种常用核心语法,都可以在上面的JavaEE进阶专栏学习,专栏正在持续更新中🏀,有问题可以写在评论区或者私信我哦~

1,IoC思想

Spring就是包含众多方法的IoC容器,容器中放的就是对象,这些对象称为Bean

还有个概念是JavaBean,这个表示的是一个Java类(类是public类型、有无参public构造方法、属性私有,提供get和set方法...),跟IoC容器中存放管理的Bean不是一回事,博客中提到的Bean都是Spring Bean
对于IoC控制反转的作用,可以通过造车的例子来理解,要造一辆车,传统程序的开发思路就是汽车依赖车身、车身依赖底盘、底盘依赖轮子

简单来说,就是在汽车类中new车身,在车身类中new底盘,在底盘类中new轮子,这是一个依赖的关系,如下图:

创建一个Spring项目,把用不到的目录和文件都删了,只留个src、.idea和pom.xml

代码如下,轮胎中有个size属性,表示轮毂尺寸,这里定义成17寸:

java 复制代码
package com.yang.ioc;

public class Main {
    public static void main(String[] args) {
        Car car = new Car();
        car.run();
    }
}
java 复制代码
package com.yang.ioc;

public class Car {
    private Framework framework;

    public Car() {
        this.framework = new Framework();
        System.out.println("car init...");
    }

    public void run(){
        System.out.println("car run...");
    }
}
java 复制代码
package com.yang.ioc;

public class Bottom {
    private Tire tire;

    public Bottom() {
        this.tire = new Tire();
        System.out.println("Bottom init...");
    }
}
java 复制代码
package com.yang.ioc;

public class Framework {
    private Bottom bottom;

    public Framework() {
        this.bottom = new Bottom();
        System.out.println("Framwork init...");
    }
}
java 复制代码
package com.yang.ioc;

public class Tire {

    private int size = 17;
    public Tire(){
        System.out.println("tire size" + size);
    }
}

运行main方法,看下执行顺序,建造顺序是轮胎 -> 底盘 -> 框架 -> 汽车,如下图:

用这种方式来进行程序开发,就有个很大的弊端:上层是非常依赖下层的,耦合非常重
例如轮毂尺寸可以选配了,把轮毂尺寸改成一个参数,让上层创建对象时传参,代码如下:

java 复制代码
public class Tire {

    private int size;
    public Tire(int size){
        this.size = size;
        System.out.println("tire size" + size);
    }
}

改动这一个地方,其他上层的代码都要改,Car、Framework、Bottom的构造方法都要改为有参的,里面传入size参数,这就是因为代码的耦合度太高了😅

要解决这个问题,就可以用到IoC的思想,上层类中不再直接去new下层类了,直接让下层直接传给上层,在main方法中统一控制对象的创建,代码如下:

java 复制代码
package com.yang.ioc;

public class Tire {

    private int size;
    public Tire(int size){
        this.size = size;
        System.out.println("tire size:" + size);
    }
}
java 复制代码
package com.yang.ioc;

public class Bottom {
    private Tire tire;

    public Bottom(Tire tire) {
        this.tire = tire;
        System.out.println("Bottom init...");
    }
}
java 复制代码
package com.yang.ioc;

public class Framework {
    private Bottom bottom;

    public Framework(Bottom bottom) {
        this.bottom = bottom;
        System.out.println("Framwork init...");
    }
}
java 复制代码
package com.yang.ioc;

public class Car {
    private Framework framework;

    public Car(Framework framework) {
        this.framework = framework;
        System.out.println("car init...");
    }

    public void run(){
        System.out.println("car run...");
    }
}
java 复制代码
package com.yang.ioc;

public class Main {
    public static void main(String[] args) {
        Tire tire = new Tire(17);
        Bottom bottom = new Bottom(tire);
        Framework framework = new Framework(bottom);
        Car car = new Car(framework);
        car.run();
    }
}

这种写法,各个类不再自己new下层依赖(对象),依赖由外部(main方法)创建好,传进去,这就用到了IoC思想(并不是Spring IoC)

使用IoC思想最主要的好处就是降低代码的耦合度,就比如后续更改代码了,让选择汽车轮毂的配色,Tire类修改后,只需要在main方法中创建对象时修改即可,如下所示:

java 复制代码
package com.yang.ioc;

public class Tire {

    private int size;
    private String color;
    public Tire(int size,String color){
        this.size = size;
        System.out.println("tire size:" + size + ",color:" + color);
    }
}
java 复制代码
package com.yang.ioc;

public class Main {
    public static void main(String[] args) {
        Tire tire = new Tire(17,"red");
        Bottom bottom = new Bottom(tire);
        Framework framework = new Framework(bottom);
        Car car = new Car(framework);
        car.run();
    }
}

2,入门案例

正常是资源谁使用谁管理,在IoC思想中就是第三方(Spring 容器)统一管理,IoC(控制反转):负责把Bean交给容器管理

在Spring MVC(五)博客中解析了图书管理系统的登录和列表展示功能,铁汁们可以从git仓库中下载,如下图,Spring-book-demo目录就是完整代码

git仓库下载链接

图书管理系统写的代码并没有使用Spring MVC,在BookController类中直接new了BookService对象,在BookService类中直接new了BookDao对象

实现IoC就要用到@Component注解,把@Component加到BookService类和BookDao类上面,Spring的IoC容器中就会创建这两个类的对象,进行管理

后续BookController类中就不需要new BookService了,BookService中也不需要new BookDao了,创建个成员变量,上面加个@Autowired注解,就可以进行DI(依赖注入),从IoC容器中取出对象,代码如下:

java 复制代码
package org.example.springbookdemo.controller;

import org.example.springbookdemo.entity.BookInfo;
import org.example.springbookdemo.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


import java.util.List;

@RequestMapping("/book")
@RestController
public class BookController {

    @Autowired
    private BookService bookService;
    @RequestMapping("/getList")
    public List<BookInfo> getList(){
        List<BookInfo> bookInfos = bookService.getList();
        return bookInfos;
    }
}
java 复制代码
package org.example.springbookdemo.service;

import org.example.springbookdemo.dao.BookDao;
import org.example.springbookdemo.entity.BookInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class BookService {

    @Autowired
    private BookDao bookDao;
    public List<BookInfo> getList(){
        List<BookInfo> bookInfos = bookDao.mockBookData();
        for(BookInfo bookInfo:bookInfos){
            if(bookInfo.getStatus() == 1){
                bookInfo.setStatusCN("可借阅");
            }else{
                bookInfo.setStatusCN("不可借阅");
            }
        }
        return bookInfos;
    }
}

3,类注解(Bean的存储和获取)

在前面的入门案例中,在类上添加了@Component注解,把对象交给IoC容器管理,Spring框架提供更丰富的注解,共有5个类注解,如下所示:

  • @Controller
  • @Service
  • @Repository
  • @Component
  • @Configuration

使用Spring框架,有个很奇妙的点,还是拿图书管理系统来说,在BookController类中,正常要通过BookController对象.getList()来调用getList()方法,但是这里并没有new BookController对象,却可以使用getList()方法
这就是因为上面加个了@RestController注解,@RestController = @ResponseBody + @Controller,Spring已经创建好BookController对象放到IoC容器中了,底层就是取出来这个对象,来调用这个getList方法

接着进入到前面的练习项目中,写代码来测试下@Controller注解,创建个UserController类,里面使用@Controller注解,代码如下:

java 复制代码
package com.yang.ioc;

import org.springframework.stereotype.Controller;

@Controller
public class UserController {

    public void hello(){
        System.out.println("hello,UserController...");
    }
}

在Spring启动类中,按住ctrl点到run方法的源码中看一下,返回值类型是ConfigurableApplicationContext,表示的就是上下文\

用ApplicationContext(应用上下文)来接收,可以理解为是应用的存储环境,ApplicationContext是ConfigurableApplicationContext的子接口

调用ApplicationContext的getBean方法,方法中传入UserController类的Class对象,拿到Bean后,调用hello方法,代码如下:

java 复制代码
package com.yang.ioc;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;

@SpringBootApplication
public class SpringIocDemoApplication {

    public static void main(String[] args) {
        ApplicationContext context = SpringApplication.run(SpringIocDemoApplication.class, args);
        UserController bean = context.getBean(UserController.class);
        bean.hello();
    }

}

getBean方法有5种不同的传参,如下图,日常使用基本上就是只使用3种,如下图:

第一种传参就是传入Bean的name(这种写法需要进行强制类型转换)

这个Bean的name是Spring给Bean起的名字,不一定跟类名相同,命名规则如下:

  1. 默认是类名的小驼峰写法,首字母变成小写,例如UserController类,Bean对象命名为userController
  2. 特殊情况:类名的前两位字符均为大写时,Bean的名称就为类名,例如ABCController类,Bean对象命名为ABCController

第二种方法就是前面使用的,传入Class对象

第三种就是传入name + Class对象,按照这三种方式拿到Bean,调用hello方法,再打印下这三个对象的地址,代码如下:

java 复制代码
package com.yang.ioc;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;

@SpringBootApplication
public class SpringIocDemoApplication {

    public static void main(String[] args) {
        ApplicationContext context = SpringApplication.run(SpringIocDemoApplication.class, args);
        UserController bean = context.getBean(UserController.class);
        bean.hello();

        UserController userController = (UserController) context.getBean("userController");
        userController.hello();

        UserController userController2 = context.getBean("userController",UserController.class);
        userController2.hello();

        System.out.println(bean);
        System.out.println(userController);
        System.out.println(userController2);
    }

}

这三个对象的地址是完全相同的,Spring中的Bean用到了单例的思想,整个 IOC 容器里,这个 userController 只会创建唯一 一个实例,getBean中传入各种参数,拿到的是同一个对象

接着测试下@Service注解,是同样的效果,如下所示:

java 复制代码
package com.yang.ioc;

import org.springframework.stereotype.Service;

@Service
public class UserService {
    public void hello(){
        System.out.println("hello,UserService...");
    }
}
java 复制代码
package com.yang.ioc;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;

@SpringBootApplication
public class SpringIocDemoApplication {

    public static void main(String[] args) {
        ApplicationContext context = SpringApplication.run(SpringIocDemoApplication.class, args);
        UserService bean = (UserService) context.getBean("userService");
        bean.hello();
    }
}

如果把Service注解删除掉,再运行启动类,就会报错,报错原因是找不到对应的Bean,如下图:

接下来就是@Configuration、@Repository、@Component注解,这里就不再赘述了,铁汁们可以自己在启动类上测试下,这里就不赘述了,代码如下:

java 复制代码
package com.yang.ioc;


import org.springframework.context.annotation.Configuration;

@Configuration
public class UserConfig {
    public void hello(){
        System.out.println("hello,UserConfig");
    }
}
java 复制代码
package com.yang.ioc;

import org.springframework.stereotype.Repository;

@Repository
public class UserRepo {
    public void hello(){
        System.out.println("hello,UserRepo...");
    }
}
java 复制代码
package com.yang.ioc;

import org.springframework.stereotype.Component;

@Component
public class UserComponent {
    public void hello(){
        System.out.println("hello,UserComponent");
    }
}

也可以不让Spring给容器中的对象命名,自己进行命名,在类注解的括号中传入字符串即可

就拿Component为例,命名为userComponent666,代码如下:

java 复制代码
package com.yang.ioc;

import org.springframework.stereotype.Component;

@Component("userComponent666")
public class UserComponent {
    public void hello(){
        System.out.println("hello,UserComponent");
    }
}

这时候在启动类中往getBean()方法中传入"userComponent"来获取Bean,就会报错(找不到对应的Bean异常),如下图:

传入"userComponent666",就可以获取成功了,如下所示:

java 复制代码
package com.yang.ioc;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;

@SpringBootApplication
public class SpringIocDemoApplication {

    public static void main(String[] args) {
        ApplicationContext context = SpringApplication.run(SpringIocDemoApplication.class, args);
        UserComponent userComponent = (UserComponent) context.getBean("userComponent666");
        userComponent.hello();
    }
}

五大类注解的区别如下:

  • @Controller:控制层,接收请求,对请求进行处理,并进行响应
  • @Service:业务逻辑层,处理具体的业务逻辑
  • @Repository:数据访问层,也称为持久层,负责数据访问操作
  • @Configuration:配置层,处理项目中的一些配置信息
  • @Component:通用组件注解,在一些业务组件上使用

类注解划分为5个,能够提高代码的可读性,打开类后看注解就知道这个类的作用(类似于车牌号前的省的别称 + 大写字母)
后端写代码时分为三层架构:表现层(controller)、 业务逻辑层(service)、数据访问层(dao)

表现层中就使用@Controller注解,业务逻辑层中就使用@Service注解,数据访问层中就使用@Repository注解(后端的三层架构在SpringMVC(五)博客中有详细的解析)
@Configuration注解,后面解析Spring配置的博客会提到

按住ctrl键进入每个注解的源码来看一下,如下图

对比下就会发现:@Controller、@Service、@Repository、@Configuration都是@Component的衍生注解,在是使用时,@Service、@Repository、@Configuration用@Component来代替,语法上是不会报错的

@Controller是不能用@Component来代替的,因为@Controller具备接收请求的能力,@Component是没有这种能力的(这里只是补充一下,实际哪个层用对应的注解即可)

类注解之间的关系如下图:

在2.入门案例的图书管理系统中,类注解加的都是@Component,现在已经解析了5个类注解的区别,就把Dao层和Service层的类注解改一下,让代码更规范,如下图:

4,方法注解

方法注解只有一个,就是@Bean

如果只使用类注解,IoC容器中只会放一个类的实例,getBean中传入各种参数,拿到的是同一个对象,那就会存在一些问题:

  • 例如在一个项目中,使用两个MySQL数据库,那就要创建两个DataSource对象,这时候就需要把这两个相同类型对象都放到IoC容器中
  • 创建依赖的对象放到IoC容器中,第三方依赖的代码是不能修改的,没办法在上面加上类注解

这两个问题,都可以通过方法注解来解决,这里写个UserInfo类,使用@AllArgsConstructor,会生成全部参数的构造方法,用这个UserInfo类来模拟只读的依赖类,代码如下:

java 复制代码
package com.yang.ioc;

import lombok.AllArgsConstructor;
import lombok.Data;

@AllArgsConstructor
@Data
public class UserInfo {
    private String name;
    private Integer age;
}

再创建一个Test类,里面写个userInfo方法和userInfo2方法,里面创建两个UserInfo对象,方法上都加上@Bean注解,这样IoC容器中就放入了两个属性不同的UserInfo对象(UserInfo类上并没有加类注解)
@Bean 所在的类,必须带有类注解,5种类注解都可以,这里用@Configuration

java 复制代码
package com.yang.ioc;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class Test {
    @Bean
    public UserInfo userInfo(){
        return new UserInfo("David",21);
    }

    @Bean
    public UserInfo userInfo2(){
        return new UserInfo("Tommy",21);
    }
}

如果容器中存在多个相同类型的Bean,直接在启动类中用Class对象来拿Bean,就会报出NoUniqueBeanDefinitionException(没有唯一的 Bean 定义异常),因为启动类分不清楚想获取的是哪个Bean,如下所示:

java 复制代码
package com.yang.ioc;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;

@SpringBootApplication
public class SpringIocDemoApplication {

    public static void main(String[] args) {
        ApplicationContext context = SpringApplication.run(SpringIocDemoApplication.class, args);
        UserInfo userInfo = context.getBean(UserInfo.class);
    }
}

这时候就必须在getBean方法中传入name了,只传入name的话需要进行强制类型转换,传入name和Class对象的话,就不需要,name就是方法名

在启动类中获取两个对象,打印一下属性,如下所示:

java 复制代码
package com.yang.ioc;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;

@SpringBootApplication
public class SpringIocDemoApplication {

    public static void main(String[] args) {
        ApplicationContext context = SpringApplication.run(SpringIocDemoApplication.class, args);
        UserInfo userInfo = context.getBean("userInfo",UserInfo.class);
        UserInfo userInfo2 = context.getBean("userInfo2",UserInfo.class);

        System.out.println(userInfo);
        System.out.println(userInfo2);
    }
}

总结一下,@Bean的应用场景就是创建依赖对象和需要为一个类创建多个对象

也可以在Bean注解中传入字符串,给Bean对象命名(这时候Bean的name就是这个传入的字符串,而不是方法的名称),如下所示:

java 复制代码
package com.yang.ioc;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class Test {
    @Bean("aaa")
    public UserInfo userInfo(){
        return new UserInfo("David",21);
    }

    @Bean("bbb")
    public UserInfo userInfo2(){
        return new UserInfo("Tommy",21);
    }
}
java 复制代码
package com.yang.ioc;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;

@SpringBootApplication
public class SpringIocDemoApplication {

    public static void main(String[] args) {
        ApplicationContext context = SpringApplication.run(SpringIocDemoApplication.class, args);
        UserInfo userInfo = context.getBean("aaa",UserInfo.class);
        UserInfo userInfo2 = context.getBean("bbb",UserInfo.class);
        System.out.println(userInfo);
        System.out.println(userInfo2);

    }
}

使用Bean注解进行命名,还可以给一个Bean起多个名,需要使用大括号,字符串之间用逗号隔开(类似于后端定义接收请求只能使用某几种方法的那种写法),代码如下:

java 复制代码
package com.yang.ioc;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;

@SpringBootApplication
public class SpringIocDemoApplication {

    public static void main(String[] args) {
        ApplicationContext context = SpringApplication.run(SpringIocDemoApplication.class, args);
        UserInfo userInfo = context.getBean("aaa2",UserInfo.class);
        UserInfo userInfo2 = context.getBean("bbb2",UserInfo.class);
        System.out.println(userInfo);
        System.out.println(userInfo2);

    }
}

5,扫描路径

前面解析5个类注解时,创建了5个测试类:UserConfig、UserController、UserInfo、UserComponent、UserService,现在创建5个包(包和启动类在同一路径下),把这5个类放到对应的包中,如下图:
铁汁们可以测试下,这种情况下是可以在启动类中拿到各个类的Bean的

如果把启动类移动到component包中,再来测试下,就会发现:只能在启动类中拿到UserComponent的Bean,是拿不到其他类的Bean,如下所示:

java 复制代码
package com.yang.ioc.component;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;

@SpringBootApplication
public class SpringIocDemoApplication {

    public static void main(String[] args) {
        ApplicationContext context = SpringApplication.run(SpringIocDemoApplication.class, args);
        UserComponent bean = context.getBean(UserComponent.class);
        bean.hello();
    }
}
java 复制代码
package com.yang.ioc.component;

import com.yang.ioc.config.UserConfig;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;

@SpringBootApplication
public class SpringIocDemoApplication {

    public static void main(String[] args) {
        ApplicationContext context = SpringApplication.run(SpringIocDemoApplication.class, args);
        UserConfig bean = context.getBean(UserConfig.class);
        bean.hello();
    }
}

铁汁们可以把启动类多移动几个包看一下,会发现每次都是只能拿到当前包中类的Bean,尝试拿其他包中类的Bean,就会报出NoSuchBeanDefinitionException(找不到对应的Bean)

原因就是Spring只能扫描当前路径(包)下的哪些类加了注解,需要创建对象放到Bean容器中,不会扫描项目中的其他路径
因此,在开发中需要注意启动类放的位置,还可以使用@ComponentScan注解,指定Spring的扫描路径,代码如下:

java 复制代码
package com.yang.ioc.component;

import com.yang.ioc.config.UserConfig;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.ComponentScan;

@ComponentScan(basePackages = "com.yang.ioc")
@SpringBootApplication
public class SpringIocDemoApplication {

    public static void main(String[] args) {
        ApplicationContext context = SpringApplication.run(SpringIocDemoApplication.class, args);
        UserConfig bean = context.getBean(UserConfig.class);
        bean.hello();
    }
}

6,DI

DI(Dependency Injection):依赖注入,容器自动给Bean注入它需要的依赖

关于依赖注入,Spring提供了三种方法:

  1. 属性注入
  2. 构造方法注入
  3. Setter注入

1,属性注入

属性注入是最简单的,直接在成员变量上加个@Autowired注解即可,就能完成Bean的注入(前面的2.入门案例使用的就是属性注入)
例如在UserController类中注入UserService对象,在UserController类的hello方法中调用UserService的hello方法,在启动类中再调用UserController类中的hello方法,代码如下:

java 复制代码
package com.yang.ioc.controller;

import com.yang.ioc.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

@Controller
public class UserController {

    @Autowired
    private UserService userService;
    
    public void hello(){
        System.out.println("hello,UserController...");
        userService.hello();
    }
}
java 复制代码
package com.yang.ioc.service;

import org.springframework.stereotype.Service;

@Service
public class UserService {
    public void hello(){
        System.out.println("hello,UserService...");
    }
}
java 复制代码
package com.yang.ioc.component;

import com.yang.ioc.controller.UserController;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.ComponentScan;

@ComponentScan(basePackages = "com.yang.ioc")
@SpringBootApplication
public class SpringIocDemoApplication {

    public static void main(String[] args) {
        ApplicationContext context = SpringApplication.run(SpringIocDemoApplication.class, args);
        UserController userController = (UserController)context.getBean(UserController.class);
        userController.hello();
    }
}

注:一个@Autowired只能引入一个Bean,如果要引入多个Bean的话,要在每个上面都加个@Autowired注解

例如要在serController类中引入UserService和UserConfig的Bean,代码如下:

java 复制代码
package com.yang.ioc.controller;

import com.yang.ioc.config.UserConfig;
import com.yang.ioc.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

@Controller
public class UserController {

    @Autowired
    private UserService userService;
    
    @Autowired 
    private UserConfig userConfig;

    public void hello(){
        System.out.println("hello,UserController...");
        userService.hello();
        userConfig.hello();
    }
}

2,构造方法注入

还可以通过有参的构造方法来完成依赖的注入,写个有参的构造方法,这个构造方法会从Spring的IoC容器中取出Bean,进行赋值,如下所示:

java 复制代码
package com.yang.ioc.controller;

import com.yang.ioc.service.UserService;
import org.springframework.stereotype.Controller;

@Controller
public class UserController {
    private UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }

    public void hello(){
        System.out.println("hello,UserController...");
        userService.hello();
    }
}

但是如果在UserController类中加上个无参的构造方法,再运行一下启动类,就会报出NullPointerException(空指针异常),如下所示:

java 复制代码
    public UserController() {
    }

报出空指针异常,是因为当有参构造方法和无参构造方法都存在时,Spring在创建UserController的Bean时,默认使用的就是无参构造方法,进而userService就不会赋值,就是null(只写了无参构造方法时,就是只有这一个选项,Spring只能选这个了)
如果在类中同时定义了有参构造方法和无参构造方法,要解决这个问题,就可以在有参构造方法上加个@Autowired注解,标记一下,让Spring在创建UserController的Bean时,使用这个有参构造方法,如下所示:

java 复制代码
package com.yang.ioc.controller;

import com.yang.ioc.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

@Controller
public class UserController {
    private UserService userService;

    @Autowired
    public UserController(UserService userService) {
        this.userService = userService;
    }

    public UserController() {
    }

    public void hello(){
        System.out.println("hello,UserController...");
        userService.hello();
    }
}

如果在UserController类中写两个有参构造方法,方法前都不加@Autowired注解,也会报错,因为Spring不知道要用哪个构造方法来创建Bean,如下图:

解决办法就是在要使用的构造方法上加上@Autowired注解

3,setter方法注入

还可以使用set方法来注入Bean,在set方法上需要加上@Autowired注解,如下所示:

java 复制代码
package com.yang.ioc.controller;

import com.yang.ioc.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

@Controller
public class UserController {
    private UserService userService;

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    public void hello(){
        System.out.println("hello,UserController...");
        userService.hello();
    }
}

一个set方法只能注入一个Bean,如果要注入多个,就需要写多个set方法,set方法上都加上@Autowired注解,如下所示:

java 复制代码
package com.yang.ioc.controller;

import com.yang.ioc.config.UserConfig;
import com.yang.ioc.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

@Controller
public class UserController {
    private UserService userService;
    private UserConfig userConfig;

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @Autowired
    public void setUserConfig(UserConfig userConfig) {
        this.userConfig = userConfig;
    }

    public void hello(){
        System.out.println("hello,UserController...");
        userService.hello();
        userConfig.hello();
    }
}

三种注入的优缺点分析:

  • 属性注入:优点是使用起来简洁,但是只能在IoC容器中使用,不能在其他框架中使用,而且不能注入一个final属性,因为final属性需要在定义属性时直接初始化(不是依赖注入了)或者在构造方法中进行初始化(属于构造方法注入)
  • 构造方法注入:通用性好,构造方法是JDK支持的,所以更换任何框架都是适用的;可以注入final属性;构造方法仅在Bean创建的时候只执行一次,Bean 建好之后,Spring 不会再调用构造方法,所以注入的对象也不会被二次修改;缺点就是代码写起来比较繁琐
  • setter方法注入:set 方法随时都能再次调用它,覆盖成员变量的值,也就是能够重新配置,但是这样也带来了注入对象被修改的风险

4,相同类型Bean的注入

通过方法注解,可以在IoC容器中放入多个相同类型的Bean,代码如下:

java 复制代码
package com.yang.ioc;

import lombok.AllArgsConstructor;
import lombok.Data;

@AllArgsConstructor
@Data
public class UserInfo {
    private String name;
    private Integer age;
}
java 复制代码
package com.yang.ioc;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class Test {
    @Bean
    public UserInfo userInfo1(){
        return new UserInfo("David",21);
    }

    @Bean
    public UserInfo userInfo2(){
        return new UserInfo("Tommy",21);
    }
}

现在IoC容器中有两个UserInfo类型的Bean,解下来就测试下在UserController类中使用属性注入,拿到的是哪个Bean

java 复制代码
package com.yang.ioc.controller;

import com.yang.ioc.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

@Controller
public class UserController {
    
    @Autowired
    private UserInfo userInfo;

    public void hello(){
        System.out.println("hello,UserController...");
        System.out.println(userInfo);
    }
}

运行启动类后,会发现程序直接就启动失败了,看一下日志,属性userInfo要求一个Bean,但是在IoC容器中发现了两个,如下图:

如果在IoC容器中有多个Bean,想注入特定的一个,就可以在创建Bean方法上面加上@Primary注解,指定注入Bean的时候获取这个,如下所示:

除了在方法上使用@Primary注解,还可以在成员变量上使用@Qualifier注解,里面传入Bean的名称,指定获取特定的Bean

还可以使用@Resource注解,来指定要注入的Bean的名称,使用@Resource注解后,就不需要使用@Autowired注解了,如下所示:

有个经典的面试题,问@Resource和@Autowired的区别:

  1. @Autowired是Spring框架提供的注释,而@Resource是JDK提供的注释
  2. @Autowired默认是按照类型注入的,@Resource是按照名称注入的(同时考虑类型和名称)

@Autowired也是可以按照名称获取的,把成员变量命名为userInfo1,就可以正确获取的Bean

只写了@Autowired时,会先根据类型来匹配,如果在IoC容器中,匹配到了多个该类型的Bean,再根据成员变量的名称来匹配

@Autowired匹配顺序如下图:

结语

IoC和DI这部分知识还是比较多的,但并不难,多写几次代码很快就能理解,截至到这篇博客,Spring的核心基础知识已经解析了一多半了,有个非常经典的面试题,问Spring,Spring MVC,Spring Boot的关系和区别,解析如下:

  • Spring是一个轻量级、模块化、一站式的开发应用框架,目的是为了简化企业应用程序的开发;主要功能是管理对象和对象间的依赖关系、面向切面编程(AOP)、数据库事务管理、数据访问、web框架支持等
    Spring具有高度的可开放性,可以很方便的使用第三方框架,例如数据访问框架(Mybatis)(AOP和Mybatis后续博客都会进行解析)
  • Spring MVC是Spring的一个子框架,是按照MVC模式来设计的,主要用于开发web应用和网络接口,因此Spring MVC是一个Web框架
    Spring MVC是基于Spring来开发的,可以让我们更简洁的进行Web层的开发,支持灵活的URL到页面控制器的映射;提供了约定大于配置的契约式编程支持(和框架之间达成一个隐形契约 ------ 按它的规矩来,它自动帮你干活,只有想打破规则时,才需要写配置);非常容易与其他视图框架集成,例如Velocity,FreeMaker
  • Spring Boot对Spring进行了封装,简化了Spring应用的开发,使用Spring Boot后,开发人员无需写大量、重复的基础配置,可以快速搭建框架,让开发变的更加简单,Spring Boot就是个脚手架,可以快速的将其他框架集成进来(Spring MVC框架、Mybatis框架)

以上就是今天的所有内容啦~完结撒花~🥳🎉🎉

相关推荐
master3363 小时前
基于 Spring AI + Spring Cloud 构建 Web 版 AI Chat:多模型接入、流式对话与全链路验证
人工智能·spring·spring cloud
骑着蜗牛撵大象3277 小时前
AgentScope 搭大脑、Spring AI 当手脚:企业智能体推理与执行分层落地
java·人工智能·spring·智能体·工具调用·agentscope·模型编排
CoderYanger7 小时前
Java EE 进阶:15. Linux基本使用和程序部署(第二弹):部署 Web 项目到 Linux
linux·服务器·数据库·spring boot·spring·阿里云·java-ee
EatFan8 小时前
2026 后端 AI 集成选型拆解:Spring AI 2.0、MCP 协议与 Agent 内嵌三条路径的决策要点
java·人工智能·spring
长不大的杨瑞杰9 小时前
Spring AI 企业级 RAG 实战:检索、重排、结构化输出与提示注入防护
java·人工智能·spring·llm·rag·springai
水巷石子12 小时前
从请求到逐字返回:用 Spring WebFlux + SSE 打通 Java 大模型的打字机流式输出
java·后端·spring
水巷石子12 小时前
从一行调用到四种入口:Spring AI 1.x ChatClient 实战与 LangChain4j 选型对比
java·人工智能·spring·langchain
会编程的吕洞宾1 天前
Spring Boot虚拟线程实战:吞吐提升3倍
java·经验分享·后端·spring
xurileidian1 天前
第 22 篇 · 边玩边学Python · 双等号与 is 不是一回事
开发语言·python·spring