上一篇是基于 @ComponentScan自动装配Bean的实现,这一篇将通过java手动装配bean来实现。
手动装配相对于自动装配的优点:
1 package soundsystem;
2 import org.springframework.context.annotation.Bean;
3 import org.springframework.context.annotation.ComponentScan;
4 import org.springframework.context.annotation.Configuration;
5
6 @Configuration
7 public class JavaConfig2 {
8 @Bean
9 public CompactDisc sgtPeppers(){
10
11 System.out.println("自行扩展业务逻辑1");
12 return new SgtPeppers();
13 }
14 @Bean
15 public CDPlayer cdplayer(){
16 //Cdplayer依赖于CompactDisc,在这里一起装配
17 System.out.println("自行扩展业务逻辑2");
18 return new CDPlayer(sgtPeppers());
19 }
20 }
二、测试java配置
测试之前将javaConfig注释掉。附测试类
package test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import soundsystem.CDPlayer;
import soundsystem.CompactDisc;
import soundsystem.MediaPlayer;
import soundsystem.SgtPeppers;
public class Test {
public static void main(String[] args) {
//基于java类中配置上下文
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(soundsystem.JavaConfig2.class);
//基于xml配置上下文
//ClassPathXmlApplicationContext context =
new ClassPathXmlApplicationContext("applicationContext.xml");
CompactDisc cd= (CompactDisc) context.getBean("sgtPeppers");
cd.play();
// MediaPlayer player=context.getBean(CDPlayer.class);
// player.play();
}
}