> For the complete documentation index, see [llms.txt](https://jack80342.gitbook.io/spring-boot/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://jack80342.gitbook.io/spring-boot/iv.-spring-boot-features/46.-creating-your-own-auto-configuration/46.3-condition-annotations/46.3.2-bean-conditions.md).

# 46.3.2 Bean条件

`@ConditionalOnBean`和`@ConditionalOnMissingBean`注解可以根据特定类是否存在决定bean的包含，你可以使用`value`属性指定beans（by type），也可以使用`name`定义beans（by name），`search`属性用于限制搜索beans时需要考虑的`ApplicationContext`层次。

当被放置在一个`@Bean`方法时，目标类型默认为方法的返回类型，例如：

```java
@Configuration
public class MyAutoConfiguration {

    @Bean
    @ConditionalOnMissingBean
    public MyService myService() { ... }

}
```

在上面的例子中，如果`ApplicationContext`里没有类型为`MyService`的bean，那么`myService`bean将会被创建。

**注** 你需要注意bean定义添加的顺序，因为这些条件的计算是基于目前处理内容的。出于这个原因，我们推荐在自动配置类上只使用`@ConditionalOnBean`和`@ConditionalOnMissingBean`注解（即使保证它们在其他用户定义的beans后加载）。

**注** `@ConditionalOnBean`和`@ConditionalOnMissingBean`不会阻止`@Configuration`类的创建，在类级别使用那些conditions跟使用注解标记每个`@Bean`方法是等价的。
