本文内容
以一个简单的案例介绍如何基于注解的手动装配搭建一个Spring开发环境
环境
Spring-4.3.2
Commons-logging-1.2
案例项目
有一台计算机(Computer),这台计算机拥有声音播放设备的接口(PlaybackDevice),和一个键盘接口(Keyboard),因此只需要给计算机装配合适的设备,这台计算机就可以使用。
播放设备接口 PlaybackDevice.java
package com.oolong.main; public interface PlaybackDevice { public void play(); public void turnUp(); public void tureDown(); }
键盘设备接口 Keyboard.java
package com.oolong.components; public interface KeyBoard { public void print(); }
计算机 Computer.java
package com.oolong.components; public class Computer { private PlaybackDevice playDevice; private KeyBoard keyBoard; public void setPlayDevice(PlaybackDevice playDevice) { this.playDevice = playDevice; } public void setKeyBoard(KeyBoard keyBoard) { this.keyBoard = keyBoard; } public void playMusic() { playDevice.play(); } public void input() { keyBoard.print(); } }
计算机有两个设备的接口,并且有设置设备的方法。此外还有一个 playMusic() 方法可以播放声音,一个 input() 方法可以输入数据。
播放设备 VoiceBox.java
package com.oolong.components; public class VoiceBox implements PlaybackDevice { public void play() { System.out.println("by Vocie Box"); } public void turnUp() { // TODO Auto-generated method stub } public void tureDown() { // TODO Auto-generated method stub } }
机械键盘 Mechanical.java
package com.oolong.components; public class Mechanical implements KeyBoard { @Override public void print() { System.out.println("Mechanical"); } }
编写配置类
ComputerConfig.java
package com.oolong.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.oolong.components.Computer; import com.oolong.components.KeyBoard; import com.oolong.components.Mechanical; import com.oolong.components.PlaybackDevice; import com.oolong.components.VoiceBox; @Configuration public class ComputerConfig { @Bean(name = "voiceBox") public PlaybackDevice playbackDevice() { return new VoiceBox(); } @Bean(name = "mechaincal") public KeyBoard keyboard() { return new Mechanical(); } @Bean(name = "computer") public Computer computer(PlaybackDevice playbackDevice, KeyBoard keyboard) { Computer computer = new Computer(); computer.setPlayDevice(playbackDevice); computer.setKeyBoard(keyboard); return computer; } }
测试
AppContainer.java
package com.oolong.computer; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import com.oolong.components.Computer; import com.oolong.config.ComputerConfig; public class AppContainer { public static void main(String[] args) { ApplicationContext ac = new AnnotationConfigApplicationContext(ComputerConfig.class); Computer computer = (Computer)ac.getBean("computer"); computer.playMusic(); computer.input(); } }
解析
Spring容器帮助我们处理bean之间的依赖关系,比如Computer这个实例化是需要依赖于一个 PlaybackDevice 和一个 Keyboard,你们我们的配置其实就是告诉Spring,如果Spring想要获取一个 PlaybackDevice 如何获取,想要获取一个 Keyboard 如何获取。
以及想要获取一个 Computer,如何获取。
当我们问Spring要一个 Computer的时候,它就会根据我们的要求交给我们一个 Computer。