Fork me on GitHub

ConditionalOnMissingBean 友好的扩展

ConditionalOnMissingBean 当没有指定的Bean时,使用当前默认的Bean
声明一个接口
/**
 * 测试服务
 */
public interface ITest {
    void test();
}

 

  提供默认实现

public class DefaultTest implements ITest {
    @Override
    public void test() {
        System.out.println(this);
    }
}

 

  当我们的业务中默认使用某个Bean

@SpringBootApplication
public class AppStart implements CommandLineRunner {
    public static void main(String[] args) {
        SpringApplication.run(AppStart.class, args);
    }

    @Resource(name = "TEST")
    private ITest test;

    /**
     * Callback used to run the bean.
     *
     * @param args incoming main method arguments
     * @throws Exception on error
     */
    @Override
    public void run(String... args) throws Exception {
        test.test();
    }
}

 

  此时又需要给外部动态扩展使用,此时显然给DefaultTest加上注解@Service("TEST")之后,外部将无法再扩展,因此提供 ConditionalOnMissingBean 来实现动态注入名称为TEST的bean服务

首先提供一个配置类

import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class DefaultBeanConfig {
    @Bean("TEST")
    @ConditionalOnMissingBean(name = "TEST")
    public ITest test() {
        return new DefaultTest();
    }
}

没有外部扩展时,默认则是 DefaultTest

 

直接扩展:

@Service("TEST")
public class CustomTest implements ITest {
    @Override
    public void test() {
        System.out.println(this);
    }
}

此时返回的是扩展的 CustomTest

 

 复用父类功能,并扩展

public class DefaultTest implements ITest {
    @Override
    public void test() {
        System.out.println("defulat"+this);
    }
}

 

@Service("TEST")
public class CustomTest extends DefaultTest {
    @Override
    public void test() {
        extracted(); // 扩展
        super.test();// 复用父类的能力
    }

    private void extracted() {
        System.out.println(this);
    }
}

 

 

 

 

posted @ 2025-07-01 23:06  黄高林  阅读(17)  评论(0)    收藏  举报