Spring的条件注入的原理及使用

2021-06-08  本文已影响0人  十毛tenmao

Spring支持按照条件来注入某些特定的bean,这也是Spring Boot实现自动化配置的底层方法

基本方法

//满足条件WindowsCondition才会注入UserManager到Spring上下文
@Component
@Conditional(WindowsCondition.class)
public class UserManager {
    XXX
}
@FunctionalInterface
public interface Condition {

    /**
     * Determine if the condition matches.
     * @param context the condition context
     * @param metadata the metadata of the {@link org.springframework.core.type.AnnotationMetadata class}
     * or {@link org.springframework.core.type.MethodMetadata method} being checked
     * @return {@code true} if the condition matches and the component can be registered,
     * or {@code false} to veto the annotated component's registration
     */
    boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata);
}

使用自定义条件

/**
 * 判断是否是Windows系统.
 */
public class WindowsCondition implements Condition {
    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        Environment environment = context.getEnvironment();
        String property = environment.getProperty("os.name");
        return property.contains("Windows");
    }
}
@Slf4j
@Component
@Conditional(WindowsCondition.class)
public class UserManager {
    @PostConstruct
    private void init() {
        log.info("UserManager init");
    }
}

参考

上一篇 下一篇

猜你喜欢

热点阅读