通过Java代码装配bean
向著某一天終于要達到的那個終極目標邁步還不夠,還要把每一步驟看成目標,使它作為步驟而起作用。
——歌德
很多場景下我們都可以通過Spring組件掃描和自動裝配的方式來裝配bean,但是在部分情況下,如使用第三方庫中的Java類時,我們沒辦法將注解添加到其Java類中,Spring也就無法掃描識別裝配bean。在這種情況下,我們就必須采用顯式配置的方式:使用Java代碼或XML配置。
在進行顯式配置時,使用Java代碼式更好的方案,因為它更強大、類型安全和友好。如下,我們創建一個GameConfig的java配置類,為其添加了@Configuration注解,表明這個類是一個配置類,作用是聲明Spring應用上下文如何創建bean細節。
package chapter2.practice2;import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration;@Configuration public class GamerConfig {@Beanpublic Game lolGames() {return new LeagueOfLegends();} }在GamerConfig類中我們使用@bean注解聲明了一個LeagueOfLegends bean,@bean注解會告訴Spring這個方法將會返回一個對象,該對象要注冊為Spring上下文的bean。值得注意的是:默認情況下,Spring中的bean都是單例的。
目前,LeagueOfLegends這個bean是非常簡單的,因為它沒有其他的依賴,下面我們給它添加一個依賴關系。
package chapter2.practice2;public class Computer {public void installGame() {System.out.println("Install the game...");} } package chapter2.practice2;public class LeagueOfLegends implements Game {private Computer computer;public void play() {computer.installGame();} }現在LeagueOfLegends類中依賴于Computer類,那么我們怎么在GanmerConfig配置類將其注入呢?
1)通過構造器注入
package chapter2.practice2;public class LeagueOfLegends implements Game {private Computer computer;public LeagueOfLegends(Computer computer) {this.computer = computer;}public void play() {computer.installGame();} } package chapter2.practice2;import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration;@Configuration public class GamerConfig {/*** 構造器注入* @return*/@Beanpublic Game lolGames() {return new LeagueOfLegends(apComputer());}/*** 構造器注入* @return*/@Beanpublic Game loGames(Computer computer) {return new LeagueOfLegends(computer);}@Bean Computer apComputer() {return new Computer();} }2)通過set方法注入
package chapter2.practice2;public class LeagueOfLegends implements Game {private Computer computer;public void setComputer(Computer computer) {this.computer = computer;}public LeagueOfLegends() {}public LeagueOfLegends(Computer computer) {this.computer = computer;}public void play() {computer.installGame();} } package chapter2.practice2;import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration;@Configuration public class GamerConfig {/*** 構造器注入* @return*/@Beanpublic Game lolGames() {return new LeagueOfLegends(apComputer());}/*** 構造器注入* @return*/@Beanpublic Game loGames(Computer computer) {return new LeagueOfLegends(computer);}/*** set方法注入* @param computer* @return*/@Beanpublic Game lGames(Computer computer) {LeagueOfLegends game = new LeagueOfLegends();game.setComputer(computer);return game;}@Bean Computer apComputer() {return new Computer();} }?
轉載于:https://www.cnblogs.com/dandelZH/p/8698325.html
總結
以上是生活随笔為你收集整理的通过Java代码装配bean的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【模板篇】数论大杂烩~
- 下一篇: 『Numpy』内存分析_高级切片和内存数