First, preface
This article undertakes the previous section: Spring_ Summary _03_ Assembly Bean (a) automatic assembly
As mentioned in the previous section, there are three ways to assemble a bean, which is first recommended for automatic assembly. When automatic assembly does not work, it is necessary to use the display configuration method.
There are two scenarios of display configuration: Java and XML. When the configuration needs to be displayed, the preferred type is secure and more powerful than XML Java configuration.
Second, Java configuration
Implementing a Java configuration takes only two steps:
(1) Declaring a configuration class with @configuration
(2) Use @bean to declare a bean in the configuration class and inject the bean through the method name.
Third, Java configuration instance
PackageCom.ray.blog.smartblog.service;ImportOrg.springframework.context.annotation.Bean;Importorg.springframework.context.annotation.Configuration;/** * @author: Shira * @date: 2018/7/27 * @time: 21:21 * @desc: **/@Configuration//1. Declaring the configuration class Public classCdplayerconfig {@Bean//2.1 declares that a bean,spring will register it as a bean in context. The bean's name defaults to the method name PublicCompactdisc Compactdisc () {return NewCompactdisc (); } @Bean (Name= "COMPACTDISC3")//2.2 You can specify the name of the bean by using the Name property PublicCompactdisc comPactDisc2 () {return NewCompactdisc (); } @Bean PublicCDPlayer CDPlayer () {return NewCDPlayer (Compactdisc ());//3.1 injects beans by referencing the method that creates the bean. By default, the beans in spring are singleton. } @Bean PublicCDPlayer CdPlayer2 (Compactdisc compactdisc) {//3.2 Inject beans with the name of the bean. In a spring container, as long as there is a bean in the container, you can inject it in the parameters of another bean's declaration method return NewCDPlayer (COMPACTDISC); } }
View Code
Spring_ summarizing the Java configuration of the _03_ assembly Bean (ii)