@ConditionalOnResource
介绍
@ConditionalOnResource
是Spring框架中的一个条件化注解,它允许你根据类路径中是否存在指定的资源来决定是否加载特定的Bean定义或配置类。这个注解可以用于类级别或方法级别。
具体@Conditional使用请看这篇文章【spring】@Conditional注解学习-CSDN博客
类似@ConditionalOnResource注解还有下面:
@ConditionalOnResource
源码
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Conditional({OnResourceCondition.class})
public @interface ConditionalOnResource {
String[] resources() default {};
}
@ConditionalOnResource
属性介绍
resources
,它是一个字符串数组,用于指定需要检查的资源路径。你可以通过这个属性来指定多个资源路径,Spring框架会检查这些资源是否存在于类路径中。
@ConditionalOnResource(resources = { "classpath:conditional-config.xml", "classpath:conditional-other-config.properties" })
resources
属性支持通配符,例如 *
和 ?
。你可以使用通配符来匹配多个资源。例如:
@ConditionalOnResource(resources = "classpath:conditional-config*.xml")
@Conditional
测试示例代码
示例代码 一
ConditionalDemo类
package com.yang.SpringTest.annotation.conditionalLearn;
import lombok.Data;
/**
* <p>description</p>
*
* @author By: chengxuyuanshitang
* Package com.yang.SpringTest.annotation.conditionalLearn
* Ceate Time 2024-03-20 14:55
*/
@Data
public class ConditionalDemo {
}
创建conditional.properties文件
ConditionalDemoConfig配置类
package com.yang.SpringTest.annotation.conditionalLearn;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnResource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
/**
* <p>配置类</p>
*
* @author By: chengxuyuanshitang
* Package com.yang.SpringTest.annotation.conditionalLearn
* Ceate Time 2024-03-20 14:54
*/
@Slf4j
@Configuration
@ConditionalOnResource(resources = "classpath:conditional.properties")
public class ConditionalDemoConfig {
@Bean
public ConditionalDemo demo() {
log.info("------------- ConditionalDemo init -------------");
return new ConditionalDemo();
}
}
ConditionalTest测试类
package com.yang.SpringTest.annotation.conditionalLearn;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import java.util.Arrays;
/**
* <p>测试类</p>
*
* @author By: chengxuyuanshitang
* Package com.yang.SpringTest.annotation.conditionalLearn
* Ceate Time 2024-03-20 14:58
*/
public class ConditionalTest{
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ConditionalDemoConfig.class);
String[] definitionNames = context.getBeanDefinitionNames();
Arrays.stream(definitionNames).forEach((definitionName) -> System.out.println(definitionName));
}
}