实现:
新建一个接口 DemoService 并用两种条件实现
/**
* 示例demo
*
* @Author: AZERO_DRH
* @Date: 2019/10/22 10:32
* @JDK 1.8
* @since 1.0.0
*/
public interface DemoService {
String demo();
}
/**
* 实现一
*
* @Author: AZERO_DRH
* @Date: 2019/10/22 10:35
* @JDK 1.8
* @since 1.0.0
*/
@Profile("one")
@Service
public class OneDemoServiceImpl implements DemoService {
@Override
public String demo() {
return "Hello,One Demo";
}
}
/**
* 实现二
*
* @Author: AZERO_DRH
* @Date: 2019/10/22 10:39
* @JDK 1.8
* @since 1.0.0
*/
@Profile("Two")
@Service
public class TwoDemoServiceImpl implements DemoService {
@Override
public String demo() {
return "Hello,Two Demo";
}
}
完成上面的实现之后,创建一个引导类测试一下。
/**
* DemoService 启动引导类
*
* @Author: AZERO_DRH
* @Date: 2019/10/22 10:42
* @JDK 1.8
* @since 1.0.0
*/
@SpringBootApplication(scanBasePackages = "com.study.durihong.service")
public class DemoServiceBootstrap {
public static void main(String[] args) {
ConfigurableApplicationContext context = new SpringApplicationBuilder(DemoServiceBootstrap.class)
.web(WebApplicationType.NONE)
// 指定条件类型 即 实现DemoService时 在实现类的上添加的@Profile("one")
.profiles("one")
.run(args);
// DemoService Bean 是否存在
DemoService Demoservice = context.getBean(DemoService.class);
System.out.println(" Demoservice.demo : " +
Demoservice.demo());
// 关闭上下文
context.close();
}
}
@SpringBootApplication(scanBasePackages = "com.study.durihong.service") 指定了扫描的路径,扫描的方式也可以是:
@ComponentScan(basePackages = "com.study.durihong.service") ,两个注解都可以指定。
就上面的代码,运行之后,显示的结果:
因为指定的Profile条件就是 one.