spring 条件装配

1.spring中可以基于某些条件装配Bean

只不过需要实现 Condition接口

package com.activity.study;

import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;

public class UserCondition implements Condition{

    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        return true;
    }

}

然后在@Bean这里我们可以使用这个条件

@Configuration
public class UserConfig {
    @Bean
    @Conditional(UserCondition.class)
    public User user() {
        return new User();
    }
        
}

 

2.根据条件的true 或者false  我们就可以基于条件装配@Bean

false会成功,true会失败

 

posted @ 2021-05-08 22:18  随意的马蒂洛克  阅读(179)  评论(0编辑  收藏  举报