In Spring Assembly

Spring container is responsible for creating the application bean and to coordinate the relationship between these objects through DI.

Assembly (wiring): Create a collaboration between the application object's behavior. It is done by DI.

Developers need to tell what you want to create Spring bean, how to assemble it together.

 

Spring There are three main assembly mechanisms:

  • Explicit assembled in XML
  • Explicit assembled in Java
  • Implicit bean discovery mechanism and automatic assembly

Three kinds of assembly methods can be used with. Priority use of automated assembly, Java explicit wiring, XML explicit wiring.

Automated assembly

Scanning component (component scanning). @Component automatically find the class with annotation, and create bean.
Automatic assembly (as autowiring)

 

Spring component scans in default does not open, you need to configure opened by Java class configuration or XML configuration file.

Java configuration class uses @ComponentScan start scanning components, by default the same package and the child package scanning and configuration classes, find the class with @Component annotated, and create bean.

@Configuration
@ComponentScan
public class CDPlayerConfig {
}

XML configuration open component scans

<context:component-scan base-package="yourpackage"/>

Java code configuration

When the assembly is fitted to the third-party library applications, you require the use of explicit assembly, automatic assembly can not be used.

@Configuration
public class CDPlayerConfig {
    @Bean(name = "lonelyHeartsClubBand")
    public CompactDisk sgtPeppers() {
        return new SgtPeppers();
    }

    @Bean
    public CDPlayer cdPlayer() {
        return new CDPlayer(sgtPeppers());
    }

    public CDPlayer cdPlayer(CompactDisc compactDisc) {
        return new CDPlayer(compactDisc);
    }
}

@Configuration table name of this class is a class configuration, which includes details on how to create the bean.

@Bean notes that the method returns an object that you want to register for the Spring context bean. The default method is the bean ID name, sgtPeppers, can also be specified by the name attribute.

 

Guess you like

Origin www.cnblogs.com/minguo/p/10889967.html