javascript
Spring Setter依赖注入示例
學習如何編寫Spring Setter依賴注入示例 。 Setter注入是Spring依賴注入的一種 。 Spring支持字段注入,Setter注入以及構造函數注入,以將依賴項注入Spring托管的bean中。 本教程的范圍僅限于Setter注入。
有關Spring依賴注入的更多信息:
- Spring構造函數依賴注入示例
- Spring字段依賴注入示例
- Spring依賴注入–字段vs設置器vs構造函數注入
- Spring依賴注入和控制反轉
考慮一下,我們有一個DogsService ,它是一個基于Spring的REST服務。
我們將編寫一個DogsController , DogsService和DogsDao 。 這是一個不執行任何操作的虛擬服務。 這里的目的是了解Spring Dependency Injection如何與Setter方法一起使用。
不知道如何編寫Spring Boot Rest Service?
閱讀: Spring Boot Rest Service
想更多地了解Spring Framework?
讀這個:
- Spring框架介紹
- Spring框架架構
- Spring依賴注入和控制反轉
- Spring靴休息服務
DogsDao.java
沒有字段,因此沒有依賴性。 我們添加了帶有打印消息的無參數構造函數。
package com.amitph.spring.dogs.dao;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;} }DogsService.java
DogsService取決于DogsDao 。 在下面的類中, setter方法用@Autowired注釋。 為了查看Setter注入的工作方式,我們在setter方法中添加了一條print語句。 除了使用setter方法外,我們還添加了無參數構造函數和帶有相應打印消息的參數化構造函數 。
package com.amitph.spring.dogs.service;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();}@Autowiredpublic void setDao(DogsDao dao) {System.out.println("DogsService setter called");this.dao = dao;}public DogsService(){System.out.println("DogsService no-arg constructor called");}public DogsService(DogsDao dao) {System.out.println("DogsService arg constructor called");this.dao = dao;} }DogsController.java
DogsController依賴于DogsService 。 設置器帶有@Autowired注釋,并具有打印語句。 除了setter方法外,我們還添加了無參數和參數化構造函數以及相應的打印消息。
package com.amitph.spring.dogs.web;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;@GetMappingpublic List<Dog> getDogs() {return service.getDogs();}@Autowiredpublic void setService(DogsService service) {System.out.println("DogsController setter called");this.service = service;} }應用啟動
. ____ _ __ _ _/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \\\/ ___)| |_)| | | | | || (_| | ) ) ) )' |____| .__|_| |_|_| |_\__, | / / / /=========|_|==============|___/=/_/_/_/:: Spring Boot :: (v2.1.0.RELEASE)2019-02-04 19:06:17.058 INFO 68545 --- [ main] com.amitph.spring.dogs.Application : Starting Application on Amitsofficemac.gateway with PID 68545 (/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:06:17.061 INFO 68545 --- [ main] com.amitph.spring.dogs.Application : No active profile set, falling back to default profiles: default 2019-02-04 19:06:17.670 INFO 68545 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data repositories in DEFAULT mode. 2019-02-04 19:06:17.724 INFO 68545 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 48ms. Found 1 repository interfaces. 2019-02-04 19:06:17.992 INFO 68545 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$4a5366ed] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying) 2019-02-04 19:06:18.225 INFO 68545 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http) 2019-02-04 19:06:18.237 INFO 68545 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat] 2019-02-04 19:06:18.237 INFO 68545 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/9.0.12 2019-02-04 19:06:18.242 INFO 68545 --- [ main] o.a.catalina.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:06:18.315 INFO 68545 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext 2019-02-04 19:06:18.315 INFO 68545 --- [ main] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1205 ms 2019-02-04 19:06:18.339 INFO 68545 --- [ main] o.s.b.w.servlet.ServletRegistrationBean : Servlet dispatcherServlet mapped to [/] 2019-02-04 19:06:18.342 INFO 68545 --- [ main] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*] 2019-02-04 19:06:18.342 INFO 68545 --- [ main] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*] 2019-02-04 19:06:18.342 INFO 68545 --- [ main] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'formContentFilter' to: [/*] 2019-02-04 19:06:18.342 INFO 68545 --- [ main] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*] 2019-02-04 19:06:18.434 INFO 68545 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting... 2019-02-04 19:06:18.524 INFO 68545 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed. 2019-02-04 19:06:18.645 INFO 68545 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default...] 2019-02-04 19:06:18.690 INFO 68545 --- [ main] org.hibernate.Version : HHH000412: Hibernate Core {5.3.7.Final} 2019-02-04 19:06:18.691 INFO 68545 --- [ main] org.hibernate.cfg.Environment : HHH000206: hibernate.properties not found 2019-02-04 19:06:18.779 INFO 68545 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.0.4.Final} 2019-02-04 19:06:18.868 INFO 68545 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQL5InnoDBDialect 2019-02-04 19:06:19.279 INFO 68545 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default' DogsDao no-arg constructor called DogsService no-arg constructor called DogsService setter called DogsController no-arg constructor called DogsController setter called 2019-02-04 19:06:19.650 INFO 68545 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor' 2019-02-04 19:06:19.681 WARN 68545 --- [ 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 this warning 2019-02-04 19:06:19.856 INFO 68545 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path '' 2019-02-04 19:06:19.859 INFO 68545 --- [ main] com.amitph.spring.dogs.Application : Started Application in 3.138 seconds (JVM running for 3.647)春天發生的事情是Spring首先嘗試實例化DogsController并發現了對DogsService的依賴。 因此,它實例化了DogsService ,而后者又依賴于DogsDao 。 因此, DogsDao是第一個實例化的,然后是DogsService ,最后是DogsController 。
讓我們詳細看看發生了什么。
- 第36行:調用DogsDao無參數構造函數。
- 第37行:調用DogsService無參數構造函數。 注意:參數化的構造函數永遠不會被調用 。
- 第38行:調用DogsService Setter。 注入DogsDao實例(在第36行創建)的位置。
- 第39行:調用DogsController無參數構造函數。
- 第40行:調用DogsController Setter方法。 DogsService實例(在第37行中創建)。
摘要
您學習了如何在Spring應用程序中編寫Setter注入 。 如果使用Setter注入 ,則使用@Autowired注釋setter方法。 Spring將首先使用無參數構造函數實例化Bean,然后調用setter方法來注入依賴項。
在接下來的教程中,我們將了解基于構造函數的注入是如何工作的。
翻譯自: https://www.javacodegeeks.com/2019/02/spring-setter-dependency-injection-example.html
總結
以上是生活随笔為你收集整理的Spring Setter依赖注入示例的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 西方经济学的研究对象是什么 西方经济学的
- 下一篇: 更深入地了解Java 8 Date an