大体步骤
1.实现java配置类。在我们的类上声明@Configuration
注解
2.编写条件。通过@Conditional
注解,来达到什么情况下创建我们需要的bean。
3.定位配置。我们需要在META/spring.factories
中声明我们的自动配置类,让springboot能够找到它。
相关注解
@Conditional
:条件注解
类条件
@ConditionalOnClass
:存在某个class时,做什么操作。
@ConditionalOnMissingClass
:不存在某个class时,做什么操作。
属性条件
@ConditionalOnProperty
:存在某个属性时,做什么操作。
bean条件
@ConditionalOnBean
:存在某个bean时,做什么操作。
@ConditionalOnMissingBean
:不存在某个bean时,做什么操作。
@ConditionalOnSingleCandidate
:单例bean时,或bean配置为primary时,做什么操作。
资源条件
@ConditionalOnResource
:在有什么资源时,做什么操作。
Web应用条件
@ConditionalOnWebApplication
:web应用,做什么操作。
动手实现
首先创建一个greeting模块
@Slf4j
public class GreetingApplicationRunner implements ApplicationRunner {
public GreetingApplicationRunner() {
log.info("Initializing GreetingApplicationRunner.");
}
public void run(ApplicationArguments args) throws Exception {
log.info("Hello everyone! We all like Spring! ");
}
}
然后再创建一个autoconfigure模块
@Configuration
// 如果存在GreetingApplicationRunner模块,该配置才能生效
@ConditionalOnClass(GreetingApplicationRunner.class)
public class GreetingAutoConfiguration {
@Bean
//GreetingApplicationRunner缺少这个class才执行该方法
@ConditionalOnMissingBean(GreetingApplicationRunner.class)
//配置greeting.enable=true才执行该方法,或者不配置也能执行,=false不执行
@ConditionalOnProperty(name = "greeting.enabled", havingValue = "true", matchIfMissing = true)
public GreetingApplicationRunner greetingApplicationRunner() {
return new GreetingApplicationRunner();
}
}
最后一个模块依赖上面两个模块
这样启动时候就能实现自动配置了。
MAVEN的scope范围
maven一共有3套classpath:编译classpath,测试classpath,运行classpath。
- compile:默认值,对于三套classpath都有效
- test:仅对测试classpath有效,因此只有在运行测试(例如junit)时才能import依赖
- provided:对于编译和测试classpath有效。意味着只需要打包时候用到,在运行是,web容器会提供。例如servlet包
- runtime:对于测试和运行classpath有效。例如jdbc。
- system:依赖范围和provided一致,但是该依赖是存放于本地,需要由systemPath元素来显示指定依赖文件的路径。
- import:maven中使用scope= import
<dependency>
<group>javax.sql</group>
<artifactId>jdbc-stdext</artifactId>
<version>2.0</version>
<scope>system</scope>
<systemPath>${JAVA_HOME}/lib/rt.jar</systemPath>
</dependency>
自己实现自动配置思路
1.实现一个配置类,用于创建一个BeanFactoryPostProcessor。
2.然后BeanFactoryPostProcessor类中,我们可以通过在里头查找,是否加载了某个class,没加载直接什么都不做。加载了,可以看看是否存在beanDefinition,然后再做什么操作。创建的某个bean的话,封装成gernicBeanDefinition,并注册。
参考
maven依赖范围scope详解
Maven依赖中的scope详解
极客时间Spring。强烈推荐。