Spring构造函数依赖注入示例

欢迎使用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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/344631.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【渝粤教育】电大中专常见病药物治疗 (2)作业 题库

1.作为退热药&#xff0c;阿司匹林的劣势是&#xff08;&#xff09;。 A.口服吸收迅速而完全 B.婴幼儿发热用阿苯片 C.儿童用药可引起Reye综合征&#xff0c;尤其是病毒性感染引起的发热 D.作用于下丘脑体温调节中枢 E.解热镇痛作用较强 错误 正确答案&#xff1a;左边查询 学…

移动通信例题整理_第3章_无线信号的衰落

考前预习,只为做题。从题目出发,补充相关概念知识点。 S1 课件例题 一、求接收功率 1、例:如果发射机发射50W的功率,将其换算成(a)dBm和(b)dBW。如果该发射机为单位增益天线,并且载频为900MHz,求出在自由空间中距天线100m处接收功率为多少dBm。10km处 P r P_r P

outlook邮箱邮件内容乱码_VBA:Outlook和Excel综合运用

很多企业公司使用微软OUTLOOK作为公司邮箱进行业务往来。 我们经常需要将一些表格数据也展示给收件人&#xff0c;但是又不需要将整个工作簿添加为附件&#xff0c;那么最好的方法就是复制指定单元格区域内容然后粘贴进新邮件界面内就可以了。 偶尔写一个邮件&#xff0c;这样做…

JDK 9、10和11中的安全性增强

缩短JDK发布周期的原因之一是有可能推出更快的安全错误修复和增强功能。 在本文中&#xff0c;我们将简要回顾一下最新JDK版本中引入的主要安全增强功能。 由于这些增强功能中的大多数与TLS相关&#xff0c;因此必须了解TLS握手过程&#xff0c;如下图所示&#xff1a; JDK 9 …

【渝粤教育】电大中专建设工程法规 (2)作业 题库

1.建造师在工作中&#xff0c; 必须严格遵守法律、行政、 行业管理规范、 职业道德。 A.正确 B.错误 正确 正确答案&#xff1a;左边查询 学生答案&#xff1a;A 2.行政法规的制定主体是&#xff08; &#xff09;。 A.全国人民代表大会 B.最高人民法院 C.全国人民代表大会及其…

【渝粤教育】电大中专新媒体营销实务 (10)作业 题库

1.从信息传播行为上来看&#xff0c;传统的报纸杂志、广播节目、电视频道等媒体&#xff0c;主要针对的是一群用户的需求。这是指新媒体的&#xff08; &#xff09;特征。 A.实时化 B.移动化 C.个性化 错误 正确答案&#xff1a;左边查询 学生答案&#xff1a;B 2.互联网媒体是…

三星q90r如何升级系统_看尚电视强制升级风行系统,如何安装第三方软件?

最近,看尚电视强制升级系统,不论界面UI还是操作方式都与之前有所不同,就连就简单的下载第三方软件,很多用户表示升级之后处处碰壁,那么今天小编就来和大家讲一下升级之后所遇到的问题,方便大家及时熟悉新系统。1、如何安装第三方软件这次看尚电视升级后,安装第三方软件的方式与…

移动通信考前预习_第4章_全球移动系统(GSM)

课件例题 例&#xff1a; 现GSM系统有10MHz的频段&#xff0c;如果采用434\times343的频率复用&#xff0c;试求出这个系统里基站的频点配置。若改成333\times333的频率复用&#xff0c;那么情况又是如何&#xff1f; 练习&#xff1a; 现GSM系统有6MHz的频段&#xff0c;如果…

【渝粤教育】电大中专沟通技巧答案作业 题库

1.&#xff08; &#xff09;给中职生就业带来的机遇和挑战 A.“十三五”规划 B.一带一路 C.发展标准化服务业 正确 正确答案&#xff1a;左边查询 学生答案&#xff1a;A 2.&#xff08; &#xff09;个人原因会影响到中职生就业。 A.清闲期望 B.高薪期望 C.一步到位做管理的期…

remote vscode无git_vs code 使用git

1.下载git https://git-scm.com/2. git 全局设置git config --global user.name "xxxx"git config --global user.email "xxxxxx.com"3.创建git 本地仓库进入指定文件夹 执行git init添加远程 地址 git remote add origin https://gitee.com/richard1015/…

appengine_在Google的AppEngine上升级到Java 7

appengine如果您仍在Google AppEngine上运行Java 6应用程序&#xff0c;则将遇到严重的麻烦。 现在&#xff0c;AppEngine团队将随时发布1.8.9版&#xff0c;该版本将不再支持Java 6应用程序的部署。 现有的应用程序将继续运行。 但是您可能应该以必要的紧迫性升级应用程序&am…

Github常用搜索指令(毕设资料搜索必备)

1、language&#xff1a;限制语言 2、in&#xff1a;根据某个关键词来进行检索 关键词name项目名称description项目描述readme项目帮助文档语法&#xff1a;需要检索的内容 in:name或description或reademe 组合使用&#xff1a;加逗号即可 3、根据starts或fork关键词查找 单…

【渝粤教育】电大中专电商运营实操 答案作业 题库

1.电子商务最重要的是&#xff08; &#xff09; A.商务 B.网站 C.货物 D.信息技术 正确 正确答案&#xff1a;左边查询 学生答案&#xff1a;A 2.目前菜鸟网络依赖大数据和云计算已实现了哪些功能&#xff08; &#xff09; A.自动化仓库 B.智能发货 C.物流云加速 D.以上都正确…

Java:以CSV格式流式传输JDBC结果集

在上一篇文章中 &#xff0c;我展示了如何将java.sql.ResultSet转换为JSON并将其流回调用方。 这篇文章是关于以CSV格式流式传输的。 流式传输使您可以一点一点地传输数据&#xff0c;而不必将所有数据都加载到服务器的内存中。 例如&#xff0c;考虑以下ResultSet &#xff1…

button onclick 多个同名_多个按钮的OnClickListener()android

您只需按照以下步骤轻松实现……您不必为每个按钮编写新的onClickListener …只需将View.OnClickLister实现到您的Activity / Fragment ..它将实现名为onClick()的新方法,用于处理Button,TextView等的onClick事件.Implement OnClickListener() in your Activity/Fragmentpublic…

Github入门学习

目的 借助github托管项目代码 基本概念 仓库&#xff08;Repository&#xff09;&#xff1a;仓库用来存放项目代码&#xff0c;每个项目对应一个仓库&#xff0c;多个开源项目则有多个仓库。 收藏&#xff08;Star&#xff09;&#xff1a;收藏项目&#xff0c;方便下次查看…

【渝粤教育】电大中专电子商务网站建设与维护 (25)作业 题库

1.目前&#xff0c;阿里巴巴集团旗下主要交易市场不包括哪个&#xff08; &#xff09; A.中国批发交易平台 B.全球批发交易平台 C.中国交易市场 D.国际交易市场 错误 正确答案&#xff1a;左边查询 学生答案&#xff1a;未作答 2.阿里巴巴是于1999年创立的&#xff08; &#…

【渝粤教育】电大中专职业应用写作作业 题库

1.每个大学生最应该具备的写作能力是&#xff08;&#xff09; A.诗歌创作 B.小说创作 C.应用文写作 D.散文创作 错误 正确答案&#xff1a;左边查询 学生答案&#xff1a;A 2.下面说法正确的是&#xff08;&#xff09; A.应用文可以发挥依据和凭证的作用 B.应用文不能规范人们…

在vscode上编写jsp_使用vscode高效编写博客园博客

图片上传可真麻烦!之前写博客的时候&#xff0c;我一般是使用马克飞象先编辑好然后直接复制粘贴到博客园中&#xff0c;这样做一方面可以一边写一遍预览改&#xff0c;另一方面可以保存到印象笔记中&#xff0c;这样一举两得&#xff0c;比较方便。可唯一的问题就在于&#xff…

dev分支和master是什么_天天用Git,分支开发你怎么弄的?

来源| juejin.im/post/6844903635533594632Git 是目前最流行的源代码管理工具。为规范开发&#xff0c;保持代码提交记录以及 git 分支结构清晰&#xff0c;方便后续维护&#xff0c;现规范git的相关操作。分支命名1、master 分支master 为主分支&#xff0c;也是用于部署生产环…