Spring summary (two) how to configure metadata-inject beans into the Spring container

There are three ways to configure metadata in Spring, and they can be mixed.

  1. XML-based configuration metadata
  2. Annotation-based configuration metadata
  3. Java-based configuration metadata. By default, the method name is the name of the Bean.

As early as a few years ago, most Java projects used XML-based methods, but now the commonly used methods are the second and third methods, and they are often used in combination.

What is annotation-based configuration metadata?

For example, the Contrller layer, Service layer, and Dao layer in the web project all correspond to the annotations you want to use. Add annotations such as @Controller, @Service, @Repository, and @Component to the corresponding classes.

ps: It should be noted that this method needs to be used in conjunction with @ComponentScan. If SpringBoot is used, the default path for scanning components is a package at the same level as Application.class

What is Java-based configuration metadata?

such as:

@Configuration
public class ApplicationConfig{

    @Bean(name = "httpClient")
    public OkHttpClient httpClientCreate() {
        return new OkHttpClient.Builder().connectTimeout(5000, TimeUnit.MILLISECONDS)
                .readTimeout(15000, TimeUnit.MILLISECONDS).writeTimeout(500, TimeUnit.MILLISECONDS).build();
    }

}

 

Guess you like

Origin blog.csdn.net/qq_28411869/article/details/85278805