The spring container is responsible for creating the beans in the application and reconciling the relationships between these objects by ID. As a developer, we need to tell spring which beans to create and how to assemble them together.
There are two ways in which bean assembly in spring
- Implicit bean discovery mechanism and automatic assembly
- Display configuration in Java code or XML
Of course, these methods can also be used together.
We test the code as follows
Compactdisc and MediaPlayer is a two interface where MediaPlayer's constructor method has a parameter type of COMPACTDISC.
We mainly test whether the implementation of Compactdisc and MediaPlayer has been injected, while the MediaPlayer interface is not satisfied with the dependence of Compactdisc
PackageCom.zcs;ImportCom.zcs.service.CompactDisc;ImportCom.zcs.service.MediaPlayer;Importorg.junit.Test;ImportOrg.junit.runner.RunWith;Importorg.springframework.beans.factory.annotation.Autowired;Importorg.springframework.test.context.ContextConfiguration;ImportOrg.springframework.test.context.junit4.SpringJUnit4ClassRunner;Import Staticjunit.framework.TestCase.assertEquals;Import StaticJunit.framework.TestCase.assertNotNull; the @RunWith (Springjunit4classrunner.class)//XML Configuration//@ContextConfiguration (locations = "Spring-config.xml")//Java code Configuration@ContextConfiguration (Classes =cdplayerconfig.class) Public classcdplayertest {@AutowiredPrivateCompactdisc cd; @AutowiredPrivateMediaPlayer player; @Test Public voidCdshouldnotbenull () {assertnotnull (CD); } @Test Public voidPlay () {assertequals ("Playing, good location", Player.play ()); }}
1. Automatic assembly
Spring implements automated assembly from two angles:
Component Scan (Componentscan): Automatically discover the beans created in the app context
Automatic assembly (autowired): Automatically satisfies the dependencies between beans
Compactdisc interface classes and implementation classes:
Public Interface Compactdisc { String play ();}
@Componentpublicclassimplements Compactdisc { private String title= "Wow good"; Private String artist= "Jay Chou"; @Override public String Play () { return ' Playing ' +title+ ' by ' + artist;} }
Mediapalyer interface classes and implementation classes
Public Interface MediaPlayer { String play ();} @Componentpublicclassimplements MediaPlayer { private Compactdisc cd; @Autowired public cdplayer (compactdisc cd) { this.cd=cd; } @Override Public String Play () { return cd.play (); }}
Configuration Class Cdplayerconfig:
@Configuration @componentscan Public class Cdplayerconfig {}
@ComponentScan function is to scan a class with @component annotations and create a bean for it. The default is to scan the class under the same package, and of course you can add parameters to specify the package name.
such as @componentscan (basepackages={"Com.zcs"}) or @componentscan (Basepackageclasses={cdplayer.class,dvdplayer.class}) (That is, the packages in which these classes are located)
The @Autowired satisfies the automatic dependency assembly and can act on any method.
The automatic assembly in the form of XML modifies the test class @contextconfiguration to load the Spring-config.xml file and is configured as follows:
<?XML version= "1.0" encoding= "UTF-8"?><Beansxmlns= "Http://www.springframework.org/schema/beans"Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"Xmlns:context= "Http://www.springframework.org/schema/context"xsi:schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd Http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd " > <BeanID= "Compactdisc"class= "Com.zcs.impl.SgtPeppers"></Bean> <BeanID= "CDPlayer"class= "Com.zcs.impl.CDPlayer"> <Constructor-argref= "Compactdisc"></Constructor-arg> </Bean> <Context:component-scanBase-package= "Com.zcs"></Beans>
2. Display Bean assembly
When you want to assemble components from a third-party library into your application, there is no way to add @component and @autowired annotations on its class, so you cannot use automated assembly scenarios.
Only Java code or XML display configuration can be selected
First, the @component on the two implementation classes, as well as the @autowired annotations on methods in the @componentscan,cdplayer class in the configuration class, can be removed.
This time the test should not pass.
Java code mode: Modify the Cdplayerconfig configuration class to:
@Configuration Public class cdplayerconfig { @Bean public compactdisc sgtpeppers () { return New sgtpeppers (); } @Bean public MediaPlayer getcdplayer () { returnnew CDPlayer (Sgtpeppers ()); }
@Bean //public MediaPlayer getcdplayer (Compactdisc compactdisc) { // return new CDPlayer ( COMPACTDISC); //}
}
The rerun test should pass, explaining that @Bean note tells Spring that this method will return an object to be registered as a bean in the spring application context. The method body contains the logic that ultimately generates the bean's real columns.
The second method is deliberately written in a strange way, it looks like the Compactdisc is obtained by invoking the Sgtpeppers () method, but not so, spring intercepts the call to the Sgtpeppers method, and in turn gets the bean created by the method directly from the context. Instead of making a real call to it every time.
For example: Add another method (test is not the same)
@Bean public MediaPlayer anothercdplayer () { returnnew CDPlayer (Sgtpeppers ()); }
These two methods rely on injected Compactdisc will be the same bean.
Of course, it's easier to understand a bit by using the annotated method in the case.
XML mode :
First Cdplayertest is XML, and the Spring-config.xml configuration file is modified as follows:
<?XML version= "1.0" encoding= "UTF-8"?><Beansxmlns= "Http://www.springframework.org/schema/beans"Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"Xmlns:context= "Http://www.springframework.org/schema/context"xsi:schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd Http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd " > <BeanID= "Compactdisc"class= "Com.zcs.impl.SgtPeppers"></Bean> <BeanID= "CDPlayer"class= "Com.zcs.impl.CDPlayer"> <Constructor-argref= "Compactdisc"></Constructor-arg>
</ Bean > < base-package= "Com.zcs"/></beans>
The configuration of the component scan mode is not removed and is not affected.
Add:
The construction method of the complex point
Modifying the construction method of Sgtpeppers
Public classSgtpeppersImplementsCompactdisc {PrivateString title= "Good location, nice staff"; PrivateString artist= "Jay Chou"; PrivateList<string> tracks=NewArraylist<>(); PublicSgtpeppers (string title, string artist, list<string>tracks) { This. title =title; This. Artist =artist; This. Tracks =tracks; } @Override PublicString Play () {return"Playing" +title+ "by" +artist; }}
Modify Spring-config.xml at the same time
<?XML version= "1.0" encoding= "UTF-8"?><Beansxmlns= "Http://www.springframework.org/schema/beans"Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"Xmlns:context= "Http://www.springframework.org/schema/context"xsi:schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd Http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd " > <BeanID= "Compactdisc"class= "Com.zcs.impl.SgtPeppers"> <Constructor-argIndex= "0"value= "Snow Wolf Lake"/> <Constructor-argIndex= "1"value= "Jacky Cheung"/> <Constructor-argIndex= "2"> <List> <value>Not the old legend</value> <value>Love is eternal.</value> </List> </Constructor-arg> </Bean> <BeanID= "CDPlayer"class= "Com.zcs.impl.CDPlayer"> <Constructor-argref= "Compactdisc"></Constructor-arg> </Bean> <Context:component-scanBase-package= "Com.zcs"/></Beans>
There are also attribute injection <property>,c and P namespaces that are not used to elaborate. The configuration of the XML is generally configured in Java code. But the display configuration with Java code will be type-safe
Reference: Spring Combat version 4th
A brief introduction to spring Bean assembly in several ways