Implementation of Java Configuration for SpringBoot

  • 2021-06-28 12:23:24
  • OfStack

Java configuration is also recommended by Spring 4.0. It can completely replace XML configuration and is recommended by SpringBoot.

The Java configuration is achieved through @Configuation and @Bean:

1. @Configuation annotation, indicating that this class is a configuration class, equivalent to the XML method of Spring

2. @Bean annotation, annotates that on the method, the current method returns an Bean

eg:

This class does not use annotations such as @Service


package com.wisely.heighlight_spring4.ch1.javaconfig;

public class FunctionService {
  public String sayHello(String world) {
    return "Hello " + world + "!";
  }
}

This class does not annotate lei with @Service or inject Bean with @Autowire


package com.wisely.heighlight_spring4.ch1.javaconfig;

public class UseFunctionService {
  
  FunctionService functionService;

  public void setFunctionService(FunctionService functionService) {
    this.functionService = functionService;
  }
  
  public String SayHello(String world) {
    return functionService.sayHello(world);
  }
}

1. Use the @Configuation annotation to indicate that this class is a configuration class

2. Annotate the method using the @Bean annotation, returning an entity, Bean, whose name is the method name.

3. When FunctionService is injected into Bean, the functionService method can be used directly.

4. The comment passes functionService as a parameter directly into UseFunctionService.In an spring container, as long as there is one Bean in the container, it can be used directly in the parameters of another Bean's declaring method.


package com.wisely.heighlight_spring4.ch1.javaconfig;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class JavaConfig {
  @Bean
  public FunctionService functionService() {
    return new FunctionService();
  }
  
  @Bean
  public UseFunctionService useFunctionService() {
    UseFunctionService useFunctionService = new UseFunctionService();
    useFunctionService.setFunctionService(functionService());
    return useFunctionService;
  }
  
  @Bean
  public UseFunctionService useFunctionService(FunctionService functionService) {
    UseFunctionService useFunctionService = new UseFunctionService();
    useFunctionService.setFunctionService(functionService);
    return useFunctionService;
  }
}

Test class:


package com.wisely.heighlight_spring4.ch1.javaconfig;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Main {
  public static void main(String[] args) {
    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(JavaConfig.class);
    UseFunctionService useFunctionService = context.getBean(UseFunctionService.class);
    System.out.println(useFunctionService.SayHello("java config"));
    context.close();
  }
}

Related articles: