Assembling beans through Java code
? In the case of explicit assembly, there are two options: Java and XML configuration, which first describes how Java is configured.
2.3.1 Creating a Configuration class
First review the previous chapter of the configuration content:
@Configurationpublicclassimplements CompactDisc { private"sgt"; private"Twinkle, twinkle, little start"; publicvoidplay() { System.out.println("title:""song:" + song); }}
? Here we remove the @componentscan annotations, leaving only the @configuration annotations, indicating that the class is a configuration class and does not contain details on how to implement the bean, and if this is the only way to run it, The test fails with a Beancreation-exception exception. The test is expected to be injected into cdplayer and compactdisc, but these beans are not created at all, because component scans will not find them. To test pass, you need to add the @ Componentscan's annotations.
2.3.2. Declaring a simple bean
To declare the bean in javaconfig, we need to add @bean annotations to the method as follows:
@Bean publicsgtPeppers(){ returnnewSgtPeppers(); }
By default, the Bean's ID is the same as the method name with the @bean annotation (this example is Sgtpeppers), and if you want to set it to a different name, you can rename the method to specify the bean's Name property @bean (name = "Othername" ) in a way to achieve.
2nd-Assembly bean-Assembly of Beans through Java code