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

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类没有任何依赖关系。 我们在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 。 控制器类还具有一个设置程序,一个无参数构造函数和一个带有各自打印语句的参数化构造函数。
注意:参数化的构造函数以@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 构造函数注入

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

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

相关文章

python用pip安装numpy mac_Mac下python安装numpy,pandas,matplotlib

numpy是数据分析的库&#xff0c;我的目的是分析股票的数据&#xff0c;Pandas 有两种自己独有的基本数据结构Series &#xff08;一维&#xff09;和 DataFrame&#xff08;二维&#xff09;&#xff0c;它们让数据操作更简单了。它也是 Python 的一个库&#xff0c;所以&…

IntelliJ IDEA for Mac工件包(artifact)中 Web facet resources 的模块名称有误,如何修改?

在工件管理界面中&#xff0c;如果某个工件包中 Web facet resources 的模块名称有误&#xff0c;如下图所示&#xff1a; 你可以在项目根目录下的 .idea/artifacts 目录下找到以工件名称命名的 xml 文件&#xff0c;找到其中含有 facet 属性的 element 标签&#xff0c;更正…

html dom 修改,HTML DOM - 修改

创建新的 HTML 元素如需向 HTML DOM 添加新元素&#xff0c;您首先必须创建该元素(元素节点)&#xff0c;然后把它追加到已有的元素上。实例This is a paragraph.This is another paragraph.var paradocument.createElement("p");var nodedocument.createTextNode(&q…

python数据处理常用函数_Python常用数据处理函数

java多线程处理 package com.copyFile; import java.io.BufferedReader;import java.io.File;import java.io.FileReader;im ... &lbrack;Android&rsqb; RelativeLayout&comma; LinearLayout&comma;FrameLayout Android RelativeLayout 属性 // 相对于给定ID控…

redis nosql_NoSql数据库:Cassandra,Mongo,Redis数据库比较

redis nosql1.什么是NoSql数据库&#xff1f; NoSql&#xff08;不仅是Sql&#xff09;数据库是可水平扩展&#xff0c;持久存储半结构或非结构化数据并具有灵活模式的非关系数据库。 这些数据库支持多种数据模型&#xff0c;例如键值&#xff0c;文档&#xff0c;列族&#xf…

SVN更新数据和提交数据的几个疑问

有以下几个问题&#xff1a; 1.我检出一份副本到本地&#xff0c;修改了几个文件&#xff0c;然后我提交到SVN服务器中&#xff0c;此时服务器是如何更新有关的数据的呢&#xff1f;是不是把原来旧的文件数据删除了&#xff0c;保存最新提交的数据呢&#xff1f; 2.假设我修改…

html转pdf后 框会消失,html或其它文件转pdf弹出打开保存框

第一步&#xff1a;下载wkhtmktopdf软件&#xff0c;安装在指定的目录&#xff0c;如&#xff1a;C:\htmlToPdf\wkhtmltopdf&#xff0c;第二步&#xff1a;把安装好的wkhtmltopdf文件目录加到环境变量Path路径中&#xff0c;public void convertFile(){HttpURLConnection con …

SVN常见问题解答

参加&#xff1a;https://subversion.apache.org/faq.zh.html

用python画一只可爱的皮卡丘_用python画一只可爱的皮卡丘实例

效果图#!/usr/bin/env python # -*- coding:utf-8 -*- from turtle import *绘制皮卡丘头部def face(x,y): """画脸""" begin_fill() penup() # 将海龟移动到指定的坐标 goto(x, y) pendown() # 设置海龟的方向 setheading(40) circle(-150, 69)…

heroku_将应用程序集成为Heroku附加组件

herokuHeroku是流行的“平台即服务”提供商&#xff0c;它为供应商提供了作为附件提供的选项。 Heroku客户可以以多种方式使用附加组件&#xff0c;但是典型的情况是“启动数据库”&#xff0c;“启动MQ”或“启动日志记录解决方案”。 将附加组件添加到您的帐户后&#xff0c;…

请把下面的列表转换为html,在python中将列表转换为HTML表的最简单方法是什么?...

我会把你的问题分成两部分&#xff1a;给定一个“平面列表”&#xff0c;生成一个子列表列表&#xff0c;其中子列表具有给定的长度&#xff0c;并且整个列表可以按“行主要”顺序(第一个和第三个示例)或“列主要”(第二个示例)排列给定一个包含字符串项的子列表列表&#xff0…

MySQL命令之mysqldump -- 数据库备份程序

文章目录命令介绍常用选项参考示例将指定数据表的数据导出为 SQL 脚本文件和文本文件将指定的多个数据表的数据导出为 SQL 脚本文件和文本文件将指定数据库导出到脚本文件中将指定的多个数据库导出到脚本文件中将指定的表导出到脚本文件中将指定数据库中的多个表的数据导出到指…

vivado 仿真_提高Vivado效率一种自研工具介绍

在之前本公众号写过两篇关于工具更新对仿真调试提高效率的文章&#xff0c;《【干货】推荐一款FPGA仿真调试鸟枪换炮的工具&#xff01;》以及《NCVerilogSimVisionVivado仿真环境搭建》&#xff0c;详细描述了Linux环境下仿真环境搭建可以缩短五倍以上的仿真时间。本文仍是实验…

spark应用程序_Sparklens:Spark应用程序优化工具

spark应用程序Sparklens是带有内置Spark Scheduler模拟器的Spark分析工具&#xff1a;它使您更容易理解Spark应用程序的可扩展性限制。 它有助于了解给定Spark应用程序使用提供给它的计算资源的效率。 它已在Qubole实施并维护。 它是开源的&#xff08; Apache License 2.0 &am…

html图片自适应浏览器高度,css如何高度自适应浏览器高度?

高度自适应就是高度能跟随浏览器窗口的大小改变而改变&#xff0c;典型的运用在一些后台界面中上面一栏高度固定用作菜单栏或导航栏&#xff0c;下面一栏高度自适应用于显示内容。在IE7及chrome、firefox等浏览器中&#xff0c;高度自适应可以利用绝对定位来解决。但一个元素是…

Windows下Maven的下载、安装及IntelliJ IDEA集成配置

文章目录下载和安装 Maven创建本地仓库配置本地仓库路径配置环境变量IDEA 中配置 Maven 的本地仓库解决IntelliJ IDEA 创建Maven项目速度慢问题下载和安装 Maven 下载地址&#xff1a;https://maven.apache.org/download.cgi 压缩包下载后&#xff0c;将压缩包解压到合适的位置…

gis里创建要素面板怎么打开_【从零开始学GIS】ArcGIS中的绘图基本操作(二)

大家好&#xff0c;我是肝教程肝到熊猫眼的三三。本系列教程的发布&#xff0c;受到了很多同学的鼓励&#xff0c;大家在后台或微信上表达出对教程的喜爱&#xff0c;这便是更新教程的最大动力。上回教程讲解了“GIS基本操作”、“创建文档&#xff06;加载数据”、“创建GIS数…

openjdk 编译_使用OpenJDK 11运行JAXB xjc编译器

openjdk 编译如文章“ 要从Java 11中删除的API ”所述&#xff0c;JDK 11不再包括 JAXB实现。 在本文中&#xff0c;我将结合使用JAXB &#xff08; 用于XML绑定的Java体系结构 &#xff09; 参考实现提供的xjc编译器和OpenJDK 11&#xff0c;将XML模式文件编译成Java类。 在J…

四川巴中中学2021高考成绩查询,巴中市高中排名(2021巴中市中学前十排名)

四川省的巴中市在我国全部革命史上面拥有超逸影响力&#xff0c;而且这所大城市也有着着悠长的历史时间。大城市内创立的普通高中不计其数&#xff0c;在其中四所普通高中成绩显著。而且这四所普通高中全是省部级示范性初中。1、通江中学在四川省巴中市漂亮的通江县&#xff0c…

unbantu上python安装步骤_如何在Ubuntu中安装Python 3.6?

Python是增长最快的主要通用编程语言。原因有很多&#xff0c;比如它的可读性和灵活性&#xff0c;易于学习和使用&#xff0c;可靠和高效。 有两个主要的Python版本被使用- 2和3 (Python的现在和未来);前者将看不到新的主要版本&#xff0c;而后者正在积极开发中&#xff0c;在…