Spring @Bean

@Configuration
public class AccountConfig {

  @Bean
  public AccountService accountService() {
    return new AccountService(accountRepository());
  }

  @Bean
  public AccountRepository accountRepository() {
    return new AccountRepository();
  }

  @Bean
  Engine engine() {
      return new Engine();
  }
  
  @Bean("engine")
  Engine getEngine() {
      return new Engine();
  }
}

1、 The @Bean annotation on a method indicates that the method creates a Spring bean.

2、The @Bean annotation on a method to define a bean. If we don’t specify a custom name, then the bean name will default to the method name.

3、For a bean with the default singleton scope, Spring first checks if a cached instance of the bean already exists, and only creates a new one if it doesn't. If we’re using the prototype scope, the container returns a new bean instance for each method call.

4、Note, that all methods annotated with @Bean must be in @Configuration classes.

参考:Spring ApplicationContext

你可能感兴趣的:(框架,spring,java,后端)