如下制作一个第三方组件:
@Configuration
public class MyfgConfig {
@Bean
@ConditionalOnMissingBean
public Myfg getMyfg(){
return new Myfg();
}
}
public class Myfg {
public void say(){
System.out.println("-------------1----------");
}
}
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.2.RELEASE</version>
<relativePath/>
</parent>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>
注意这里不要引入springboot的插件,用maven原生的,否则使用maven install的时候,其他工程引入不进去
在另外一个工程中maven引入:
<dependency>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
用Import注解注入到此spring容器中,启动之后,看打印日志是:
我们再添加两个类:
@Configuration
public class MongodbConfig {
@Bean
public Myfg getMongoTemplate(){
return new MongoTemplateCz();
}
}
public class MongoTemplateCz extends Myfg {
@Override
public void say() {
System.out.println("-------------2----------");
}
}
再次启动,看打印日志:
至此,完美覆盖了 第三方组件的bean ,所以@ConditionalOnMissingBean提高了第三方组件的可扩展性