1.简单介绍
Spring提供了三种装配机制:
1.在XML中进行显式配置;
2.在java中进行显式配置;
3.隐式的bean发现机制和自动装配。
其中,1和3项在项目中经常使用,而在java中进行显示配置方式很少使用。本文专门介绍第2种方式。
如果在项目中,我们需要将第三方库装配到spring中,这时候就没法使用隐式装配方式(没法在第三方库中加@Component等注解),这时候,
就需要在两种显式配置中选方法配置。
其中在java中进行显式配置方式是更好的方案,因为它更为强大、类型安全并且重构友好。并且当需要装配bean非常多的时候,放在xml配置文件
不方便管理,使用java配置只需把所有javaConfig放在一个包下,扫描这个包即可。
2.代码实现
1.applicationContext-service.xml 扫描JavaConfig包
1
2.CDPlayer.java
1 packagecom.taozhiye.JavaConfigTemp;2
3 public interfaceCDPlayer {4
5 public voidget();6
7 }
3.SgtPeppers.java
1 packagecom.taozhiye.JavaConfigTemp;2
3 public class SgtPeppers implementsCDPlayer {4 @Override5 public voidget() {6 System.out.println("SgtPeppers");7 }8
9 }
4.WhiteAlbum.java
1 packagecom.taozhiye.JavaConfigTemp;2
3 public class WhiteAlbum implementsCDPlayer {4
5 @Override6 public voidget() {7 System.out.println("WhiteAlbum");8 }9
10 }
5.JavaConfig.java 需要扫描本文件所在包
1 packagecom.taozhiye.JavaConfig;2
3 importorg.springframework.context.annotation.Bean;4 importorg.springframework.context.annotation.Configuration;5
6 importcom.taozhiye.JavaConfigTemp.CDPlayer;7 importcom.taozhiye.JavaConfigTemp.SgtPeppers;8 importcom.taozhiye.JavaConfigTemp.WhiteAlbum;9
10 @Configuration11 public classJavaConfig {12
13 @Bean(name = "CDPlayer")14 publicCDPlayer get(){15 int choice = (int) Math.floor(Math.random()*2);16 System.out.println("choice:"+choice);17 if(choice == 0){18 return newSgtPeppers();19 }else{20 return newWhiteAlbum();21 }22 }23 }
6.JavaConfigAction.java
1 packagecom.taozhiye.controller;2
3 importorg.springframework.beans.factory.annotation.Autowired;4 importorg.springframework.stereotype.Controller;5 importorg.springframework.web.bind.annotation.RequestMapping;6 importorg.springframework.web.bind.annotation.ResponseBody;7
8 importcom.taozhiye.JavaConfigTemp.CDPlayer;9
10
11 @Controller12 public classJavaConfigAction {13
14 @Autowired(required = false)15 publicCDPlayer CDPlayer;16
17 @RequestMapping("getCDPlayer")18 public@ResponseBody String getCDPlayer(){19 System.out.println(CDPlayer);20 if(CDPlayer!=null){21 CDPlayer.get();22 }23 return "CDPlayer";24 }25 }
这样就完成了简单的java中进行显式配置。