@ConditionalOnMissingBean使用方式
时间: 2023-11-14 19:07:51 浏览: 49
@ConditionalOnMissingBean 是 Spring Boot 中的一个注解,用于在某个 Bean 不存在时才会创建当前 Bean。它的使用方式如下:
1. 在类上使用 @ConditionalOnMissingBean 注解,表示当指定的 Bean 不存在时才会创建当前 Bean。
2. 在方法上使用 @ConditionalOnMissingBean 注解,表示当指定的 Bean 不存在时才会创建当前方法所在的 Bean。
示例代码如下:
```java
@Configuration
public class MyConfiguration {
@Bean
@ConditionalOnMissingBean(MyService.class)
public MyService myService() {
return new MyServiceImpl();
}
}
```
上述代码中,当容器中不存在 MyService 类型的 Bean 时,才会创建 MyService 类型的 Bean。
相关问题
@ConditionalOnMissingBean
@ConditionalOnMissingBean 是 Spring Boot 中的一个注解,它可以用来控制 Bean 的创建。当一个 Bean 已经存在时,@ConditionalOnMissingBean 注解可以防止该 Bean 被创建。它常用于在系统中只需要使用默认 Bean 的情况下,避免创建重复的 Bean。
举个例子,假设我们在 Spring Boot 项目中需要使用一个名为 "userService" 的 Bean,并且我们已经定义了一个 "userService" 的实现类。如果我们想要在系统中只使用默认的 Bean,而不是使用我们自己定义的 Bean,就可以使用 @ConditionalOnMissingBean 注解来控制 Bean 的创建。具体实现方式如下:
```java
@Service
@ConditionalOnMissingBean(UserService.class)
public class DefaultUserService implements UserService {
// ...
}
```
这样,当系统中已经存在名为 "userService" 的 Bean 时,就会使用已经存在的 Bean,而不会创建新的 DefaultUserService 实例。
@ConditionalOnMissingBean(RestTemplate.class)不生效
@OnMissingBean(RestTemplate.class)不生效的原因可能是因为在使用@ConditionalOnMissingBean注解时,没有正确配置相关的条件。根据引用中的定义,@ConditionalOnMissingBean注解可以接受两个属性值:value和type。value属性可以指定一个或多个Class类型,而type属性可以指定一个或多个字符串。这两个属性值用于过滤掉已存在的Bean。
引用提供了@ConditionalOnMissingBean注解的三种使用方式。其中,注释掉的两种方式分别使用了type属性和value属性进行过滤。如果你想要过滤掉的Bean的类型是RestTemplate.class,你可以尝试使用其中一种方式。
另外,引用中的示例展示了如何在@Configuration类中调整Bean的声明顺序。你可以参考这个示例来确保@ConditionalOnMissingBean注解的Bean被正确声明在代码的末尾位置。
总结起来,要使@ConditionalOnMissingBean注解生效,你需要确保正确配置了相关的条件,并将注解的Bean声明在正确的位置。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)