通过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 { @Bean public 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 */ @Bean public Game lolGames() { return new LeagueOfLegends(apComputer()); } /** * 构造器注入 * @return */ @Bean public 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 */ @Bean public Game lolGames() { return new LeagueOfLegends(apComputer()); } /** * 构造器注入 * @return */ @Bean public Game loGames(Computer computer) { return new LeagueOfLegends(computer); } /** * set方法注入 * @param computer * @return */ @Bean public Game lGames(Computer computer) { LeagueOfLegends game = new LeagueOfLegends(); game.setComputer(computer); return game; } @Bean Computer apComputer() { return new Computer(); } }