欢迎使用Spring构造函数依赖注入示例指南。 基于构造器的依赖注入是Spring 依赖注入的一种 。 依赖注入的另一种类型是Setter注入和字段注入。

有关Spring依赖注入的更多信息:

  • Spring二传手注射的例子
  • Spring田间注入
  • 依赖注入–构造函数与现场注入
  • 依赖注入和控制反转

基于构造函数的依赖注入

它是Spring Dependency Injection的一种 ,其中对象的构造函数用于注入依赖项。 这种注入方式比较安全,因为如果不存在依赖项或无法解决依赖项,则不会创建对象。

要理解, 基于构造函数的依赖注入在Spring中是如何工作的-很明显-我们需要一个Spring应用程序。 考虑一下,我们有一个非常简单的Spring应用程序,称为DogsService ,这是一个虚拟服务。

不知道如何编写Spring Boot Rest Service?
阅读: Spring Boot Rest Service

想更多地了解Spring Framework?
读这个:

  • Spring框架介绍
  • Spring框架架构
  • Spring Bean–单例与原型
  • Spring自动布线

狗狗DAO

DAO类没有任何依赖关系。 我们在print语句中添加了无参数构造函数。

 import com.amitph.spring.dogs.repo.Dog;  import org.springframework.stereotype.Component;  import java.util.List;  @Component  public class DogsDao { public DogsDao(){ System.out.println( "DogsDao no-arg constructor called" ); } public List<Dog> getAllDogs() { System.out.println( "DogsDao.getAllDogs called" ); return null ; }  } 

狗服务

服务HAS-A DogsDao 。 服务类具有setter方法, 无参数构造函数和带有相应打印语句的参数化构造函数
注意:参数化的构造函数以@Autowrired注释。

 import com.amitph.spring.dogs.dao.DogsDao;  import com.amitph.spring.dogs.repo.Dog;  import org.springframework.beans.factory.annotation.Autowired;  import org.springframework.stereotype.Component;  import java.util.List;  @Component  public class DogsService { private DogsDao dao; public List<Dog> getDogs() { System.out.println( "DogsService.getDogs called" ); return dao.getAllDogs(); } public void setDao(DogsDao dao) { System.out.println( "DogsService setter called" ); this .dao = dao; } public DogsService(){ System.out.println( "DogsService no-arg constructor called" ); } @Autowired public DogsService(DogsDao dao) { System.out.println( "DogsService arg constructor called" ); this .dao = dao; }  } 

狗的控制器

控制器HAS-A DogsService 。 控制器类还具有一个setter,一个无参数构造函数和一个带有相应打印语句的参数化构造函数。
注意:参数化的构造函数以@Autowrired注释。

 import com.amitph.spring.dogs.repo.Dog;  import com.amitph.spring.dogs.service.DogsService;  import org.springframework.beans.factory.annotation.Autowired;  import org.springframework.web.bind.annotation.GetMapping;  import org.springframework.web.bind.annotation.RequestMapping;  import org.springframework.web.bind.annotation.RestController;  import java.util.List;  @RestController  @RequestMapping ( "/dogs" )  public class DogsController { private DogsService service; @GetMapping public List<Dog> getDogs() { return service.getDogs(); } public void setService(DogsService service) { System.out.println( "DogsController setter called" ); this .service = service; } public DogsController(){ System.out.println( "DogsController no-arg constructor called" ); } @Autowired public DogsController(DogsService service) { System.out.println( "DogsController arg constructor called" ); this .service = service; }  } 

运行应用程序

启动应用程序时,我们应该在控制台上看到以下日志。

 2019 - 02 - 04 19 : 56 : 46.812 INFO 68906 --- [          main] com.amitph.spring.dogs.Application      : Starting Application on Amitsofficemac.gateway with PID 68906 (/Users/aphaltankar/Workspace/personal/dog-service-jpa/out/production/classes started by aphaltankar in /Users/aphaltankar/Workspace/personal/dog-service-jpa)  2019 - 02 - 04 19 : 56 : 46.815 INFO 68906 --- [          main] com.amitph.spring.dogs.Application      : No active profile set, falling back to default profiles: default  2019 - 02 - 04 19 : 56 : 47.379 INFO 68906 --- [          main] .sdrcRepositoryConfigurationDelegate : Bootstrapping Spring Data repositories in DEFAULT mode.  2019 - 02 - 04 19 : 56 : 47.428 INFO 68906 --- [          main] .sdrcRepositoryConfigurationDelegate : Finished Spring Data repository scanning in 45ms. Found --- [          main] .sdrcRepositoryConfigurationDelegate : Finished Spring Data repository scanning in 45ms. Found 1 repository interfaces.  2019 - 02 - 04 19 : 56 : 47.682 INFO 68906 --- [          main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$EnhancerBySpringCGLIB$86296a04] is not eligible for getting processed by all BeanPostProcessors ( for example: not eligible for auto-proxying)  2019 - 02 - 04 19 : 56 : 47.931 INFO 68906 --- [          main] osbwembedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)  2019 - 02 - 04 19 : 56 : 47.944 INFO 68906 --- [          main] o.apache.catalina.core.StandardService  : Starting service [Tomcat]  2019 - 02 - 04 19 : 56 : 47.944 INFO 68906 --- [          main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/ 9.0 . 12  2019 - 02 - 04 19 : 56 : 47.949 INFO 68906 --- [          main] oacatalina.core.AprLifecycleListener  : The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [/Users/aphaltankar/Library/Java/Extensions:/Library/Java/Extensions:/Network/Library/Java/Extensions:/System/Library/Java/Extensions:/usr/lib/java:.]  2019 - 02 - 04 19 : 56 : 48.021 INFO 68906 --- [          main] oaccC[Tomcat].[localhost].[/]      : Initializing Spring embedded WebApplicationContext  2019 - 02 - 04 19 : 56 : 48.021 INFO 68906 --- [          main] osweb.context.ContextLoader           : Root WebApplicationContext: initialization completed in 1158 ms  2019 - 02 - 04 19 : 56 : 48.042 INFO 68906 --- [          main] osbwservlet.ServletRegistrationBean : Servlet dispatcherServlet mapped to [/]  2019 - 02 - 04 19 : 56 : 48.045 INFO 68906 --- [          main] osbwservlet.FilterRegistrationBean  : Mapping filter: 'characterEncodingFilter' to: [/*]  2019 - 02 - 04 19 : 56 : 48.046 INFO 68906 --- [          main] osbwservlet.FilterRegistrationBean  : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]  2019 - 02 - 04 19 : 56 : 48.046 INFO 68906 --- [          main] osbwservlet.FilterRegistrationBean  : Mapping filter: 'formContentFilter' to: [/*]  2019 - 02 - 04 19 : 56 : 48.046 INFO 68906 --- [          main] osbwservlet.FilterRegistrationBean  : Mapping filter: 'requestContextFilter' to: [/*]  2019 - 02 - 04 19 : 56 : 48.136 INFO 68906 --- [          main] com.zaxxer.hikari.HikariDataSource      : HikariPool- 1 - Starting...  2019 - 02 - 04 19 : 56 : 48.230 INFO 68906 --- [          main] com.zaxxer.hikari.HikariDataSource      : HikariPool- 1 - Start completed.  2019 - 02 - 04 19 : 56 : 48.322 INFO 68906 --- [          main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [ name: default ...]  2019 - 02 - 04 19 : 56 : 48.366 INFO 68906 --- [          main] org.hibernate.Version                   : HHH000412: Hibernate Core { 5.3 . 7 .Final}  2019 - 02 - 04 19 : 56 : 48.366 INFO 68906 --- [          main] org.hibernate.cfg.Environment           : HHH000206: hibernate.properties not found  2019 - 02 - 04 19 : 56 : 48.461 INFO 68906 --- [          main] o.hibernate.annotations.common.Version  : HCANN000001: Hibernate Commons Annotations { 5.0 . 4 .Final}  2019 - 02 - 04 19 : 56 : 48.546 INFO 68906 --- [          main] org.hibernate.dialect.Dialect           : HHH000400: Using dialect: org.hibernate.dialect.MySQL5InnoDBDialect  2019 - 02 - 04 19 : 56 : 48.960 INFO 68906 --- [          main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'  DogsDao no-arg constructor called  DogsService arg constructor called  DogsController arg constructor called  2019 - 02 - 04 19 : 56 : 49.304 INFO 68906 --- [          main] ossconcurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'  2019 - 02 - 04 19 : 56 : 49.330 WARN 68906 --- [          main] aWebConfiguration$JpaWebMvcConfiguration : spring.jpa.open-in-view is enabled by default . Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable . Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable . Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning  2019 - 02 - 04 19 : 56 : 49.479 INFO 68906 --- [          main] osbwembedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''  2019 - 02 - 04 19 : 56 : 49.482 INFO 68906 --- [          main] com.amitph.spring.dogs.Application      : Started Application in 3.003 seconds (JVM running for 3.521 ) 
  • 第27行:正如预期的那样,调用了DAO的无参数构造函数。
  • 第28行:调用了DogsService的参数化构造函数, DogsService在第27行创建了DAO实例。
  • 第29行:调用了控制器的参数化构造函数,并在第28行创建了服务实例。

请注意,Spring 不会调用设置器无参数构造器依赖项是通过 构造函数 纯粹注入的 。 此方法优于Spring中的Spring Setter注入和Field注入 。

摘要

在这个Spring构造函数依赖注入示例指南中,您学习了基于构造函数依赖注入Spring应用程序中如何工作。 我们还使用构造函数注入编写了可执行代码。

当构造函数用于在对象上设置实例变量时,称为构造函数注入。 在深入使用Spring Framework之前,重要的是要了解Setter注入与字段注入与构造函数注入之间的区别 。

快乐编码!

翻译自: https://www.javacodegeeks.com/2019/02/spring-constructor-dependency-injection-example.html

Spring构造函数依赖注入示例相关推荐

  1. spring 构造函数注入_Spring构造函数依赖注入示例

    spring 构造函数注入 欢迎使用Spring构造函数依赖注入示例指南. 基于构造器的依赖注入是Spring 依赖注入的一种 . 依赖注入的另一种类型是Setter注入和字段注入. 有关Spring ...

  2. Spring Setter依赖注入示例

    学习如何编写Spring Setter依赖注入示例 . Setter注入是Spring依赖注入的一种 . Spring支持字段注入,Setter注入以及构造函数注入,以将依赖项注入Spring托管的b ...

  3. Spring字段依赖注入示例

    学习如何编写Spring Field Injection示例 . 字段注入是Spring框架 依赖注入的一种 . 在本教程中,我们将编写几个类,并看一看现场注入工程. 有关Spring依赖注入的更多信 ...

  4. 梦想成现实:用xUnit.net在单元测试中实现构造函数依赖注入

    英文关键词:Constructor Dependency Injection and Unit Testing(为了方便英文搜索) 自从博客园开发团队将开发架构迁移至DDD(领域驱动开发),就开始正式 ...

  5. spring学习(34):构造函数依赖注入

    目录结构 pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns=&quo ...

  6. spring学习(25):通过构造函数依赖注入

    目录结构 pox.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns=&quo ...

  7. spring注入私有字段_Spring字段依赖注入示例

    spring注入私有字段 了解如何编写Spring Field Injection示例 . 字段注入是Spring框架 依赖注入的一种 . 在本教程中,我们将编写几个类,并看一看现场注入工程. 有关S ...

  8. Spring【依赖注入】就是这么简单

    前言 在Spring的第二篇中主要讲解了Spring Core模块的使用IOC容器创建对象的问题,Spring Core模块主要是解决对象的创建和对象之间的依赖关系,因此本博文主要讲解如何使用IOC容 ...

  9. 一次由Spring构造注入引发的错误Parameter 1 of constructor in org.rongyilian.service.impl.VerificationCodeService

    SrpringBoot服务启动后报错如下: Description:Parameter 1 of constructor in org.rongyilian.service.impl.Verifica ...

最新文章

  1. 我所经历的京东618
  2. Microbiome:揩老鼠皮毛揩来高分文章——野生哺乳动物的皮肤和肠道微生物群对环境污染做出的反应
  3. 【笔记】MAC上使用onedrive遇到的问题及解决方法
  4. matplotlib 横坐标只显示整数_matplotlib初学:这样画折线图和添加标注、箭头
  5. Spring扫描类过程解析和案例
  6. c++中的 单例模式(singleton)和双检测锁(Double-Checked Locking)
  7. tp5.0路由route.php,thinkphp5.1使用Route路由
  8. Servlet方法详解
  9. 2017.9.11 数列 失败总结
  10. 【Java并发编程】16、ReentrantReadWriteLock源码分析
  11. uiactionsheet 代理_iOS UIActionSheet (点击事件笔记)
  12. Python:货币转换(写一个程序进行人民币和美元货币之间的币值转换)
  13. Ubuntu安装 Killer Wireless-AC 1550 Wireless 无线网卡驱动
  14. 奇异值分解(SVD)
  15. 【kali】34 WEB渗透——扫描工具w3af_console
  16. 怎么用计算机直接截图,电脑怎么截图?使用电脑截图的多种方法
  17. 承上启下的总结+从吴军的书《态度》总结出的20条为人方法生活状态
  18. Apache Hudi调研小记
  19. STM32cubemax的下载与配置
  20. 编程中汉字编码和英文编码的语言融合

热门文章

  1. 牛客练习赛 61(待补F-点分治?)
  2. 【树形DP】没有上司的晚会 (ssl 1607)
  3. 初级Java开发与架构之间的差距不仅仅是开发时间
  4. 优秀 Java 程序员写代码的风格
  5. Docker部署运行微服务
  6. HTML5表格简单应用案例之[招聘需求表]
  7. 最全三大框架整合(使用映射)——IDeptService.java
  8. sql server模糊查询、分组
  9. 2020蓝桥杯省赛---java---B---6(分类计数)
  10. 第2步 安装git 配置git用户 git的安装和项目的建立