SpringBoot依赖注入的三种方式

 更新时间:2023年04月18日 09:29:16   作者:左林右李02  
本文将通过代码示例详细介绍SpringBoot依赖注入的三种方式,对学习依赖注入有一定的参考价值,需要的朋友可以参考一下

SpringBoot依赖注入的三种方式

1.使用 XML 配置依赖注入

在 Spring Boot 中,使用 XML 配置依赖注入(DI)时,需要使用<bean>元素来定义 bean,并使用<property>元素来为 bean 的属性注入值或依赖对象。

以下是一个简单的示例:

  • 在src/main/resources目录下创建applicationContext.xml文件。
  • 在该文件中定义一个 testBean bean,并注入一个 String 类型的属性name和一个 UserService 类型的依赖对象。
<?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="testBean" class="com.example.demo.TestBean">
       <property name="name" value="小明"/>
       <property name="userService" ref="userService"/>
   </bean>

   <bean id="userService" class="com.example.demo.UserService"/>

</beans>
  • 在 TestBean 类中声明一个 name 属性和一个 UserService 的依赖:
public class TestBean {
    private String name;
    private UserService userService;
    //setter和getter方法省略
}
  • 在启动类中调用 ApplicationContext 的构造函数并传入 applicationContext.xml 文件的路径,然后通过 getBean 方法获取 TestBean 实例,并访问它的属性和方法:
public class DemoApplication {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        TestBean testBean = (TestBean)context.getBean("testBean");
        String name = testBean.getName();
        UserService userService = testBean.getUserService();
        //使用testBean和userService进行其他操作
    }
}

这样就完成了 Spring Boot 中使用 XML 配置依赖注入的过程。需要注意的是,在 Spring Boot 中,官方推荐使用 JavaConfig(基于 Java 类的配置方式)或注解(Annotation)来进行依赖注入,因为它们更加方便和易于维护。

2.使用 Java 配置类实现依赖注入

使用 Java Config 实现依赖注入可以通过@Configuration和@Bean注解来实现。

以下是一个简单的示例:

  • 创建一个配置类,并使用@Configuration注解标记,定义两个 Bean:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class AppConfig {
    @Bean
    public TestBean testBean() {
        return new TestBean("小明");
    }

    @Bean
    public UserService userService() {
        return new UserServiceImpl();
    }
}
  • 定义 TestBean 类,并在该类中声明一个 name 属性:
public class TestBean {
    private String name;

    public TestBean(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
  • 定义 UserService 接口和它的实现类 UserServiceImpl:
public interface UserService {
    void addUser();
}

public class UserServiceImpl implements UserService {
    @Override
    public void addUser() {
        System.out.println("Add user success");
    }
}
  • 在启动类中使用 AnnotationConfigApplicationContext 获取配置类对象,然后使用 getBean() 方法获取 TestBean 和 UserService 实例:
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class DemoApplication {
    public static void main(String[] args) {
        ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
        TestBean testBean = context.getBean(TestBean.class);
        String name = testBean.getName();
        UserService userService = context.getBean(UserService.class);
        userService.addUser();
    }
}

这样就完成了使用 JavaConfig 实现依赖注入的过程。需要注意的是,JavaConfig 等价于 XML 配置文件,但是 JavaConfig 更加的面向对象,更加灵活,更加易于维护。

3.使用注解来进行依赖注入

可以使用注解来进行依赖注入,常用的注解有@Autowired和@Qualifier。

以下是一个简单的示例:

  • 定义一个 Service 类,使用@Autowired注解注入TestBean:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class Service {
    @Autowired
    private TestBean testBean;

    public String getName() {
        return testBean.getName();
    }
}
  • 定义 TestBean 类,测试注入是否成功:
import org.springframework.stereotype.Component;

@Component
public class TestBean {
    private String name = "小明";

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
  • 在启动类中使用 AnnotationConfigApplicationContext 获取配置类对象,然后使用 getBean() 方法获取 Service 实例:
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class DemoApplication {
    public static void main(String[] args) {
        ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
        Service service = context.getBean(Service.class);
        System.out.println(service.getName());
    }
}

运行启动类,可以看到控制台输出:

小明

这样就完成了使用注解进行依赖注入的过程。需要注意的是,使用注解可以使代码更加简洁、易于阅读和维护,但是需要注意注解的使用和作用范围。

以上就是SpringBoot依赖注入的三种方式的详细内容,更多关于Java SpringBoot依赖注入的资料请关注脚本之家其它相关文章!

相关文章

  • JAVA正则表达式校验qq号码的方法

    JAVA正则表达式校验qq号码的方法

    Java作为一种开发语言,有许多值得推荐的地方,但是它一直以来没有自带对正则表达式的支持。下面小编给大家带来了JAVA正则表达式校验qq号码的方法,需要的朋友参考下吧
    2018-04-04
  • Springboot初始化启动报错Error creating bean with name 'dataSource' defined in class path resource

    Springboot初始化启动报错Error creating bean with name 'da

    这篇文章主要为大家介绍了Springboot初始化启动报Error creating bean with name 'dataSource' defined in class path resource解决,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-08-08
  • 关于mybatis调用存储过程获取返回值问题

    关于mybatis调用存储过程获取返回值问题

    这篇文章主要介绍了mybatis调用存储过程获取返回值问题,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2022-01-01
  • 如何将maven项目划分为多个模块

    如何将maven项目划分为多个模块

    这篇文章主要介绍了如何将maven项目划分为多个模块,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-09-09
  • SpringBoot @SpringBootTest加速单元测试的小诀窍

    SpringBoot @SpringBootTest加速单元测试的小诀窍

    这篇文章主要介绍了SpringBoot @SpringBootTest加速单元测试的小诀窍,具有很好的参考价值,对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-11-11
  • Java多线程定时器Timer原理及实现

    Java多线程定时器Timer原理及实现

    这篇文章主要介绍了Java多线程定时器Timer原理及实现,涉及Timer的schedule的使用,定时器Timer的schedule等相关内容以及代码示例,具有一定参考价值,需要的朋友可以了解下。
    2017-11-11
  • Java MyBatis实战之QueryWrapper中and和or拼接技巧大全

    Java MyBatis实战之QueryWrapper中and和or拼接技巧大全

    在Java中QueryWrapper是MyBatis-Plus框架中的一个查询构造器,它提供了丰富的查询方法,其中包括and和or方法,可以用于构建复杂的查询条件,这篇文章主要给大家介绍了关于Java MyBatis实战之QueryWrapper中and和or拼接技巧的相关资料,需要的朋友可以参考下
    2024-07-07
  • Maven项目如何打包成Docker镜像?三种常用插件详解

    Maven项目如何打包成Docker镜像?三种常用插件详解

    想知道如何将Maven项目高效打包成Docker镜像吗?本文详细对比了docker-maven-plugin、jib-maven-plugin和spring-boot-maven-plugin三种方式,手把手教你从配置pom.xml到运行容器,帮你根据需求轻松选择最适合的Maven打包Docker镜像方案
    2026-07-07
  • 基于spring mvc请求controller访问方式

    基于spring mvc请求controller访问方式

    这篇文章主要介绍了spring mvc请求controller访问方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-09-09
  • SpringBoot中的ImportSelector类动态加载bean详解

    SpringBoot中的ImportSelector类动态加载bean详解

    这篇文章主要介绍了SpringBoot中的ImportSelector类动态加载bean详解,ImportSelector接口是spring中导入外部配置的核心接口,根据给定的条件(通常是一个或多个注释属性)判定要导入那个配置类,在spring自动化配置和@EnableXXX中都有它的存在,需要的朋友可以参考下
    2024-01-01

最新评论