Spring Boot Learning 1.3 - SpringBoot add components to the container

Step 1: Create a folder in the project master class configuration file, and then create a Service file, which contains the components we need, such as we add HelloService file, in which the class is created, create the component class does not need to complete the current operate

Generally, we are in the xml configuration file by adding the container label, we create a spring xml configuration file in the resource directory springboot, as shown: ,

Then add the following tag, id and path definitions for the location assembly

<bean id = "HelloService" class = "com.example.demo.Service.HelloService"> </ bean> 
was then added in the main program such annotations @ImportResource (locations = { "classpath: beans.xml"}), this will add a component.

Then add the following code in the test file:

@Test
public void testHelloService(){
    boolean helloService = ioc.containsBean("helloService");
    System.out.println(helloService);
}   

Then click on the test program, output in the field to see the assembly exists.

In springboot best use of the vessel is arranged to add class components:

Create a folder in a master class configuration, use @Configuration annotation, specifies the current configuration class is a class, so that you can replace the above configuration file.

The return value of the method added to the vessel, the vessel assembly this default name is the name of this method

public class AppConfig {
    @Bean
    public HelloService helloService(){
        System.out.println("配置类@Bean容器中添加组件");
        return new HelloService();
    }
}

Then beans.xml profile may be commented previously introduced in the main program code

Click on the test program Test the start button, you can see in the output field:

 

Published 58 original articles · won praise 31 · views 40000 +

Guess you like

Origin blog.csdn.net/qq_37504771/article/details/95260064