@ConditionalOnMissingBean
时间: 2023-10-17 20:19:14 浏览: 63
@ConditionalOnMissingBean is a Spring Boot annotation that is used to conditionally register a bean of a particular class only if no other bean of that class has been registered.
The annotation is typically used in combination with @Bean to create a new bean only if no other bean of the same class has been created by the application context. The annotation can also be used with other conditional annotations to further refine the conditions under which the bean should be created.
For example, the following code creates a new bean of type MyService only if no other bean of that type has been registered:
```
@Configuration
public class MyAppConfig {
@Bean
@ConditionalOnMissingBean
public MyService myService() {
return new MyService();
}
}
```
In this case, the @ConditionalOnMissingBean annotation ensures that the myService() method is only executed if no other bean of type MyService has been registered. If another bean of that type exists, the spring framework will not execute this method and will use the existing bean instead.
阅读全文