首页 > 其他分享 > springboot Condition 动态value

springboot Condition 动态value

时间:2022-09-18 21:36:43浏览次数:71  
标签:springboot springframework value context org import annotation Condition

package com.example.demo.condtion;

import org.springframework.context.annotation.Conditional;

import java.lang.annotation.*;

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Conditional(ClassCondition.class)
public @interface ConditionOnClass {
    String [] value();
}



package com.example.demo.config;

import com.example.demo.condtion.ClassCondition;
import com.example.demo.condtion.ConditionOnClass;
import com.example.demo.domian.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;

@Configuration
public class UserConfig {

    @Bean
    @ConditionOnClass("redis.clients.jedis.Jedis")
    public User user(){
        return  new User();
    }
}




package com.example.demo.condtion;

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

import java.util.Map;


public class ClassCondition implements Condition {

    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        // 需求导入jedis  坐标后创建UserBean
//    boolean flag =true;
//        try {
//        Class<?> aClass = Class.forName("redis.clients.jedis.Jedis");
//    } catch (ClassNotFoundException e) {
//        e.printStackTrace();
//        flag =false;
//    }
//        return flag;
//}


    // 需求导入获取注解 value 值
        Map<String, Object> map = metadata.getAnnotationAttributes(ConditionOnClass.class.getName());
        String [] value =(String []) map.get("value");
        boolean flag =true;
        try {
            for (String className : value) {
                Class<?> aClass = Class.forName(className);
            }

    } catch (ClassNotFoundException e) {
        e.printStackTrace();
        flag =false;
    }
        return flag;
}
}

 

标签:springboot,springframework,value,context,org,import,annotation,Condition
From: https://www.cnblogs.com/wscp/p/16705852.html

相关文章