首页 > 其他分享 >springboot Condition

springboot Condition

时间:2022-09-18 20:33:38浏览次数:88  
标签:springboot demo springframework context org import public Condition

package com.example.demo.config;

import com.example.demo.condtion.ClassCondition;
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
    @Conditional(ClassCondition.class)
    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 redis.clients.jedis.Jedis;


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;
    }
}



package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {

        ConfigurableApplicationContext context = SpringApplication.run(DemoApplication.class, args);
        //Object redisTemplate = context.getBean("redisTemplate");
        Object User = context.getBean("user");
        System.out.println(User);

    }

}

 

标签:springboot,demo,springframework,context,org,import,public,Condition
From: https://www.cnblogs.com/wscp/p/16705672.html

相关文章