Spring装配bean(在java中进行显式配置)

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中进行显式配置。

posted @ 2017-04-05 08:54  港城人民  阅读(2037)  评论(0编辑  收藏  举报