Skip to content

❤️ 自动依赖注入

  • @ConditionalOnMissingBean 允许用户自己注入 MyComponent,如果不指定,用户自己注入 MyComponent 时会报错
java
@Configuration
@ConditionalOnMissingBean(MyComponent.class)
public class MyComponentAutoConfiguration {
    @Bean
    public MyComponent myComponent() {
        return new MyComponent();
    }
}
  • resources/META-INF/spring.factories 添加自动配置(如果你不配置,那只有当用户的 @ComponentScan 扫描到时,才会加载 MyComponent)
org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.example.MyComponentAutoConfiguration