0
点赞
收藏
分享

微信扫一扫

Django回顾【六 】

高子歌 2023-12-06 阅读 36

自动装配

Condition:

在这里插入图片描述
SpringBootCondition:springboot自带的实现类

public final boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        String classOrMethodName = getClassOrMethodName(metadata);

        try {
            ConditionOutcome outcome = this.getMatchOutcome(context, metadata);
            this.logOutcome(classOrMethodName, outcome);
            this.recordEvaluation(context, classOrMethodName, outcome);
            return outcome.isMatch();
        } catch (NoClassDefFoundError var5) {
            throw new IllegalStateException("Could not evaluate condition on " + classOrMethodName + " due to " + var5.getMessage() + " not found. Make sure your own configuration does not rely on that class. This can also happen if you are @ComponentScanning a springframework package (e.g. if you put a @ComponentScan in the default package by mistake)", var5);
        } catch (RuntimeException var6) {
            throw new IllegalStateException("Error processing condition on " + this.getName(metadata), var6);
        }
    }

正式:

创建类Guser,

package com.example.service.service;

import com.example.controller.conditionOnclass;
import com.example.entity.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class Guser {
    @conditionOnclass("hunter")
    @Bean
    public User user(){
        return new User();
    	}
   	}
}

注解@conditionOnclass接口:指定范围,存在时间,文档,@Conditional
A注解上的B注解可以做用到A注解注解的方法上

package com.example.controller;

import org.springframework.context.annotation.Conditional;
import java.lang.annotation.*;

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

自定义一个Condition演示原理的类:创建一个实现了Condition接口的类

package com.example.controller;

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

import java.util.Map;

public class myConditional implements Condition {

    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
//        获得指定注解上面的参数值(即jar包,且可能有多个)
        Map<String,Object> map= metadata.getAnnotationAttributes(conditionOnclass.class.getName());
        String[] strings=(String[])map.get("value");
        try{
//            遍历出来jar包,然后通过反射进行获取,如果没有获取到就进行返回false的处理
            for (String className: strings
                 ) {
                Class<?> aClass=Class.forName(className);
            }
        }catch (ClassNotFoundException e){
            return false;
        }
        return true;
    }
}

举报

相关推荐

0 条评论