@ConditionalOnMissingBean 实现默认注入类
时间: 2023-11-14 14:27:18 浏览: 48
@ConditionalOnMissingBean 是 Spring Framework 提供的注解,用于在没有指定 Bean 的情况下进行默认注入。当容器中不存在某个特定的 Bean 时,@ConditionalOnMissingBean 注解可以让 Spring 自动装配一个默认的 Bean 实例。
下面是一个简单的示例:
```java
@Service
@ConditionalOnMissingBean(DefaultService.class)
public class CustomService implements IService {
// 实现自定义的服务逻辑
}
```
在上述示例中,如果容器中不存在 DefaultService 类的 Bean,那么 CustomService 类将会被自动注入为默认的 IService 实现类。如果容器中已经存在了 DefaultService 类的 Bean,则 CustomService 类不会被注入为默认实现。
通过 @ConditionalOnMissingBean 注解,我们可以灵活地控制 Bean 的装配行为,以便根据特定条件选择合适的默认实现。
相关问题
@ConditionalOnMissingBean 作用
@ConditionalOnMissingBean是一个用于修饰bean的注解,它的作用是当你的bean被注册之后,如果注册相同类型的bean,就不会成功,它会保证你的bean只有一个实例。如果你注册多个相同的bean,就会出现异常,以此来告诉人员。一般来说,对于自定义的配置类,我们应该加上@ConditionalOnMissingBean注解,以避免多个配置同时注入的风险。如果你想要注册多个相同类型的bean,可以使用@Primary来确定你要哪个实现。@Primary标识哪个是默认的bean。
举个例子,假设我们有一个AutoConfig类,其中包含了两个AMapper类型的bean:aMapper1和aMapper2。如果我们在aMapper1上面标识了@ConditionalOnMissingBean(AMapper.class),那么当我们进行aMapper2注册时,系统会出现异常,因为AMapper类型的bean只能有一个实现。如果我们想要注册多个相同类型的bean,可以使用@Primary来确定哪个是默认的bean。
```java
@Component
public class AutoConfig {
@Bean
public AConfig aConfig() {
return new AConfig("lind");
}
@Bean
@ConditionalOnMissingBean(AMapper.class)
public AMapper aMapper1(AConfig aConfig) {
return new AMapperImpl1(aConfig);
}
@Bean
@Primary
public AMapper aMapper2(AConfig aConfig) {
return new AMapperImpl2(aConfig);
}
}
```
ConditionalOnMissingBean
`@ConditionalOnMissingBean` 是 Spring Boot 提供的一个条件注解,用于在 Spring 容器中检查是否已经存在指定类型的 bean。当不存在该类型的 bean 时,才会将该 bean 注入到容器中。
例如:
```java
@Service
@ConditionalOnMissingBean(UserService.class)
public class DefaultUserService implements UserService {
// ...
}
```
上面的代码片段中,`@ConditionalOnMissingBean` 注解会检查是否已经存在类型为 `UserService` 的 bean,如果不存在,则将 `DefaultUserService` 注入到容器中。如果已经存在,则该 bean 不会被注入。
这个注解常用于默认实现类的注入。如果用户已经自己定义了一个 `UserService` 的实现类,在 Spring 容器中就已经存在了该类型的 bean,此时就可以使用 `@ConditionalOnMissingBean` 注解来注入默认实现类,以避免冲突。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.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)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)