Automated assembly Bean 1.0
Spring configuration options:
Assembly is dependent on the nature of the DI injection, Spring assembly mechanism provides the following three injection:
- To be explicitly configured in the XMl
- To be explicitly configured in java
- Bean implicit discovery mechanism and automatic assembly
Automated assembly Bean:
Spring from two angles to automate the assembly:
- Component scans (the Component Scanning): the Spring Bean will be used in the context created by auto-discovery.
- Automatic assembly (as autowiring): the Spring automatically satisfy the dependencies between the bean.
Example:
CD and CDPlayer, if you do not insert the CD into (injected) into the player, the CD player is actually not much use, so to say, a CD player is dependent on the CD to complete its mission.
package com.CDDemo; //CD的接口 public interface CompactDisc { public void play(); }
package com.CDDemo; import org.springframework.stereotype.Component; //CD的实现类 歌曲 @Component public class SgtPeppers implements CompactDisc { private String title = "sgt"; private String song = "Twinkle, twinkle, little start"; public void play() { System.out.println("title:" + title + "song:" + song); } }
package com.CDDemo; import org.springframework.stereotype.Component; //CD的实现类 歌曲 @Component public class SgtPeppers implements CompactDisc { private String title = "sgt"; private String song = "Twinkle, twinkle, little start"; public void play() { System.out.println("title:" + title + "song:" + song); } }
package com.CDDemo; //测试类 import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import static org.junit.Assert.assertNotNull; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = CDPlayerConfig.class) public class CDTest { @Autowired private CompactDisc cd; @Test public void cdShouldNotBeNull() { assertNotNull(cd); cd.play(); } }
Note that the above:
@Configuration
Spring assembly defines rules
@ComponentScan
The default configuration with the same scanning type package (herein scanning package com.CDDemo; the same package, and all of the following sub-packets).
Find out the class with @Component annotated so that we can find CompactDisc (notes because its example) and create a Bean for it in Spring.
Of course, you can also enable component scans through XML configuration way: