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

时间:2023-03-09 03:53:04
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包

 <context:component-scan base-package="com.taozhiye.JavaConfig"></context:component-scan>

  

  2.CDPlayer.java

 package com.taozhiye.JavaConfigTemp;

 public interface CDPlayer {

     public void get();

 }

  3.SgtPeppers.java

 package com.taozhiye.JavaConfigTemp;

 public class SgtPeppers implements CDPlayer {
@Override
public void get() {
System.out.println("SgtPeppers");
} }

  4.WhiteAlbum.java

 package com.taozhiye.JavaConfigTemp;

 public class WhiteAlbum implements CDPlayer {

     @Override
public void get() {
System.out.println("WhiteAlbum");
} }

  5.JavaConfig.java  需要扫描本文件所在包

 package com.taozhiye.JavaConfig;

 import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import com.taozhiye.JavaConfigTemp.CDPlayer;
import com.taozhiye.JavaConfigTemp.SgtPeppers;
import com.taozhiye.JavaConfigTemp.WhiteAlbum; @Configuration
public class JavaConfig { @Bean(name = "CDPlayer")
public CDPlayer get(){
int choice = (int) Math.floor(Math.random()*2);
System.out.println("choice:"+choice);
if(choice == 0){
return new SgtPeppers();
}else{
return new WhiteAlbum();
}
}
}

  6.JavaConfigAction.java

 package com.taozhiye.controller;

 import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody; import com.taozhiye.JavaConfigTemp.CDPlayer; @Controller
public class JavaConfigAction { @Autowired(required = false)
public CDPlayer CDPlayer; @RequestMapping("getCDPlayer")
public @ResponseBody String getCDPlayer(){
System.out.println(CDPlayer);
if(CDPlayer!=null){
CDPlayer.get();
}
return "CDPlayer";
}
}

这样就完成了简单的java中进行显式配置。