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 <context:component-scan base-package="com.taozhiye.JavaConfig"></context:component-scan>
2.CDPlayer.java
1 package com.taozhiye.JavaConfigTemp; 2 3 public interface CDPlayer { 4 5 public void get(); 6 7 }
3.SgtPeppers.java
1 package com.taozhiye.JavaConfigTemp; 2 3 public class SgtPeppers implements CDPlayer { 4 @Override 5 public void get() { 6 System.out.println("SgtPeppers"); 7 } 8 9 }
4.WhiteAlbum.java
1 package com.taozhiye.JavaConfigTemp; 2 3 public class WhiteAlbum implements CDPlayer { 4 5 @Override 6 public void get() { 7 System.out.println("WhiteAlbum"); 8 } 9 10 }
5.JavaConfig.java 需要掃描本文件所在包
1 package com.taozhiye.JavaConfig; 2 3 import org.springframework.context.annotation.Bean; 4 import org.springframework.context.annotation.Configuration; 5 6 import com.taozhiye.JavaConfigTemp.CDPlayer; 7 import com.taozhiye.JavaConfigTemp.SgtPeppers; 8 import com.taozhiye.JavaConfigTemp.WhiteAlbum; 9 10 @Configuration 11 public class JavaConfig { 12 13 @Bean(name = "CDPlayer") 14 public CDPlayer get(){ 15 int choice = (int) Math.floor(Math.random()*2); 16 System.out.println("choice:"+choice); 17 if(choice == 0){ 18 return new SgtPeppers(); 19 }else{ 20 return new WhiteAlbum(); 21 } 22 } 23 }
6.JavaConfigAction.java
1 package com.taozhiye.controller; 2 3 import org.springframework.beans.factory.annotation.Autowired; 4 import org.springframework.stereotype.Controller; 5 import org.springframework.web.bind.annotation.RequestMapping; 6 import org.springframework.web.bind.annotation.ResponseBody; 7 8 import com.taozhiye.JavaConfigTemp.CDPlayer; 9 10 11 @Controller 12 public class JavaConfigAction { 13 14 @Autowired(required = false) 15 public CDPlayer 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中進行顯式配置。