Spring构造函数依赖注入示例

本文介绍了Spring框架中构造函数依赖注入的概念和工作原理。通过一个示例展示了如何使用构造函数注入创建并管理对象,强调了它相对于setter注入和字段注入的安全性。详细解释了在DogsService、DAO、服务和控制器类中的应用,并在运行应用程序时观察到的构造函数调用顺序。
摘要由CSDN通过智能技术生成

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

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

基于构造函数的依赖注入

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

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

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

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

狗狗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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值