The spring container is responsible for creating the beans in the application and reconciling the relationships between these objects through DI
Spring provides three main assembly mechanisms:
- Explicit configuration in XML
- Explicit configuration in Java
- Implicit bean discovery mechanism and automatic assembly
2 explicitly configured in Java
Although it is a much more recommended way to automate assembly of spring by component scanning and automatic assembly in many scenarios, when you want to assemble components from third-party libraries into your application, you must explicitly configure the Bean
Explicit configuration includes: Java and XML, and I recommend using Java class configuration, as in Javaconfig above
Javaconfig differs from other Java code, Javaconfig is just the configuration code, which means that it does not contain any business logic, usually putting javaconfig in a separate package, separating it from the program logic
Declaring a simple bean
The
Declares the Bean in Javaconfig, and we need to write a method that returns an instance (object) of the desired type, and then adds @Bean annotations
to this method
1 CD Class @component ("CD1")//parentheses to the bean set the ID, if not set the default is the class name first lowercase is cdpublic class CD {private String title = "The Most dazzling national wind"; Private String artist = "Phoenix Legend"; public void Play () {System.out.println ("Current play:" + title + "Singer:" + artist); }}2 CDPlayer player @component ("CDPlayer") public class CDPlayer {private CD cd; @Autowired Public CDPlayer (CD CD) {this.cd = CD; public void Play () {cd.play (); }}3 Javaconfig Configuration Class @componentpublic class Javaconfig {@Bean//If the bean ID is not declared, the default method name is the bean ID GETCD public CD getcd ( ) {return new CD (); } @Bean//bean ID getcdplayer public cdplayer getcdplayer (CD CD)//Inject the required CD class instance in the form of a parameter {return new Cdplay ER (CD); }}4 test class public class TestCase {@Test public void test01 () {Annotationconfigapplicationcontext context = new A Nnotationconfigapplicationcontext (Javaconfig.class); CDPlayer CP = (cdplayer) context.getbean ("Getcdplayer"); Cp.play (); }}
5 Console Console Results
Current play: The most dazzling national wind Singer: Phoenix legend
Spring assembly bean--02 to assemble beans through Java code