1 Automated Assembly Beans
Spring通过两个方面实现对bean的自动装配1 ) 组件扫描(component scaning):Spring会自动发现Spring上下文中的bean2 ) 自动装配(autowriting):Spring自动满足bean之间的依赖
1.1 Creating discoverable Beans
现在我们创建一个接口:
Public Interface Compactdisc { void play ();}
Then comes an implementation class:
import org.springframework.stereotype.Component; /** * Created by Cao Zhiguo on 2017/9/1. */ @Component public class Sgtpeppers implements Compactdisc { private String title= "Enjoy lonely Music" private String article= "play a harmonious chapter" public void play () {System.out.println (title +article); }
The implication of the @component annotation above is that it declares that the class is a bean, and spring has the right to manage the object, but in general we need to let the spring container know that the class is a bean, and that the presence of this annotation is not enough. Because the spring container is not able to find this annotation, you can turn on the annotation scanning mode, which is turned off by default. The same way the annotations are opened and the opportunity XML is configured: for example, we are cdplayer this automatic annotation scan in this class, as shown below: Because we want to use the Sgtpeppers object in this class.
Package cn.czg.springdemo02; Import Org.springframework.context.annotation.ComponentScan; Import org.springframework.context.annotation.Configuration; /** * Created by Cao Zhiguo on 2017/9/1. */ @Configuration @componentscan Public class Cdplayconfig {}
The function of the @configuration annotation in the above is to configure; @ComponentScan is to turn on annotation scanning, which by default is all classes under the same package as all classes or sub-packages under that object.
Here's how the XML-based configuration works:
<?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 " > <Context:component-scanBase-package= "Cn.czg.springdemo02"/></Beans>
We can do the appropriate tests.
Packagecn.czg.springdemo02;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.assertNotNull;/*** Created by Cao Zhiguo on 2017/9/1.*/@RunWith (Springjunit4classrunner.class) @ContextConfiguration (Classes= Cdplayconfig.class) Public classcdplayertest {@AutowiredPrivateCompactdisc cd; @Test Public void Test () {assertnotnull (CD); }}
The tests in the above:
1) The SPRINGJUNIT4 test is used
2) The function of @ContextConfiguration (classes = Cdplayconfig.class) is to go to the class Cdplayerconfig to load the configuration, Because the annotations @componenscan annotations are included in the Cdplayerconfig.
3) So we end up with the assertion test, which contains the Compactdisc object in the test bean. The test was apparently passed by spring to assemble the bean itself. All add-on annotations @component are beans, and using componentscan annotations you can turn on scanning. Some of the annotations and their roles we've used so far have been summed up:
@Component org.springframework.stereotype.Component; Dependent Context Package
@Configuration org.springframework.context.annotation.Configuration; Dependent Context Package
@ComponentScan Org.springframework.context.annotation.ComponentScan; Dependent Context Package
@RunWith (Springjunit4classrunner.class) Org.junit.runner.RunWith; dependent on the JUnit package and the Spring test package
@ContextConfiguration (classes = cdplayconfig.class)
Org.springframework.test.context.junit4.SpringJUnit4ClassRunner; Dependent Test Package
@Autowired org.springframework.beans.factory.annotation.Autowired; Dependent Bean Package
@Test org.junit.Test; Relying on JUnit testing
1.2 Naming the bean scanned by the component
When using XML to configure beans, we typically use the ID as the bean's unique identity, but using annotations can also be implemented:
Packagecn.czg.springdemo02;Importorg.springframework.stereotype.Component;/*** Created by Cao Zhiguo on 2017/9/1.*/@Component ("Loneiest") Public classSgtpeppersImplementsCompactdisc {PrivateString title= "Enjoy the Music of Solitude"; PrivateString article= "a harmonious chapter"; @Override Public voidPlay () {System.out.println (title+article); }}
In @componenet ("xxx") to name the Bean, as a unique identity, you can also use spring's dependency injection to complete.
Packagecn.czg.springdemo02;Importjavax.inject.Named;/*** Created by Cao Zhiguo on 2017/9/1.*//*@Component ("Loneiest")*/@Named ("Loneiest") Public classSgtpeppersImplementsCompactdisc {PrivateString title= "Enjoy the Music of Solitude"; PrivateString article= "a harmonious chapter"; @Override Public voidPlay () {System.out.println (title+article); }}
1.3 Set up the base package for component scanning
我们面临的问题是在上述的代码中,我们所有的类都在相同的包中进行的测试,因此@ComponentScan是没有任何属性的,但是如果我们要扫描不同的包该怎么实现呢?
比如说我要装配的bean在不同的包中,此时我们就要为这个注解添加属性了。基础包:就是以配置类所在的包为基础包,比如上述的代码我们要配置CDPlayerConfig类,因此他所在的包就是base-Package.但是如果我们的bean不在这个基础包中就尴尬了。
我们的做法有下面的几种方式:
Package cn.czg.springdemo02; Import Org.springframework.context.annotation.ComponentScan; Import org.springframework.context.annotation.Configuration; /** * Created by Cao Zhiguo on 2017/9/1. */ @Configuration @componentscan ("cn.czg.springdemo02") Public class Cdplayconfig {}
There's another way: set up the base package. Both ways are the same.
Package cn.czg.springdemo02; Import Org.springframework.context.annotation.ComponentScan; Import org.springframework.context.annotation.Configuration; /** * Created by Cao Zhiguo on 2017/9/1. */ = "cn.czg.springdemo02")publicclass cdplayconfig {}
As you can see, the basepackages is a plural form, so you can scan different packages in the form of arrays.
Package cn.czg.springdemo02; Import Org.springframework.context.annotation.ComponentScan; Import org.springframework.context.annotation.Configuration; /** * Created by Cao Zhiguo on 2017/9/1. */ = {"Cn.czg.springdemo02", "Cn.czg.gosaint"})publicclass Cdplayconfig {}
However, the above practice is still unsafe, only the IDE may prompt you, but the less intelligent IDE should not prompt you, because your base package uses a string type, so what type can be written, so it is like the following approach, directly scan the specific class.
Packagecn.czg.springdemo02;ImportOrg.springframework.context.annotation.ComponentScan;Importorg.springframework.context.annotation.Configuration;/*** Created by Cao Zhiguo on 2017/9/1.*/@Configuration/*@ComponentScan (basepackages = {"Cn.czg.springdemo02", "Cn.czg.gosaint"})*/@ComponentScan (basepackageclasses={Compactdisc.class, Sgtpeppers.class}) Public classCdplayconfig {}
It's better to do this a bit because the code is refactoring, it is possible that the package has changed, but the specific class is unchanged, and our scan is still correct. More secure.
1.4 Automatic assembly by adding annotations to beans
Use of annotations for @Autowird
Packagecn.czg.springdemo02;Importorg.springframework.beans.factory.annotation.Autowired;Importorg.springframework.stereotype.Component;/*** Created by Cao Zhiguo on 2017/9/2.*/@Component Public classCDPlayerImplementsMediaPlayer {PrivateCompactdisc SC; @Autowired PublicCDPlayer (Compactdisc SC) { This. sc =SC; } Public voidPlay () {sc.play (); }}
Here the Cdplay constructor in the process of building the object, at the same time the SC with parameters passed in, to inject. This is instantiated by the constructor and automatically assembles the bean.
@Autowired annotations can be used not only on constructors, but also on setter methods or on any method. is also a sign of this kind of injection relationship. Let's take a look at the usage of these two ways.
Packagecn.czg.springdemo02;Importorg.springframework.beans.factory.annotation.Autowired;Importorg.springframework.stereotype.Component;/*** Created by Cao Zhiguo on 2017/9/2.*/@Component Public classCDPlayerImplementsMediaPlayer {PrivateCompactdisc SC; @Autowired PublicCDPlayer (Compactdisc SC) { This. sc =SC; } /*** Setter Method *@paramSC*/@Autowired Public voidSETSC (Compactdisc SC) { This. sc =SC; } /*** General amount of common method *@paramSC*/@AutowiredPrivate voidInsert (Compactdisc SC) { This. sc=SC; } Public voidPlay () {sc.play (); }}
For the next section, we will verify that the automatic assembly is set up.
Assembly-DAYS01 of the Bean in the Spring Combat series