关于java:SpringBoot中Bean自动装配原理

4次阅读

共计 2404 个字符,预计需要花费 7 分钟才能阅读完成。

原理:

是通过 Condition 接口判断 pom.xml 有没有导入某个坐标或者依赖某个坐标而进行加载某个 bean。

Condition 是 Spring4.0 后引入的条件化配置接口,通过实现 Condition 接口能够实现有条件的加载相应的 Bean,

而后通过 @Conditional 注解,要配和 Condition 的实现类(ClassCondition)进行应用

需要

在 spring 的 ioc 容器中有一个 User 的 Bean,如果 pom.xml 导入了 Jedis 坐标后,就加载该 Bean,否则不加载

代码实现:

1、先创立一个 user 对象

public class User {}

2、创立一个 UserConfig.java 的配置类,生成 User 对象的 Bean

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class UserConfig {
    @Bean
    public User user(){return new User();
    }
}

3、在 Springboot 的启动类中获取 User 对象的 Bean

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 run = SpringApplication.run(DemoApplication.class, args);
       // 在 Springboot 的启动类中获取 User 对象的 Bean
        Object user = run.getBean("user");
        System.out.println(user);// 输出:com.example.demo.User@6724cdec
    }
}

以上是不论什么时候都能加载 User 对象的 Bean, 然而咱们的需要是如果 pom.xml 导入了 Jedis 坐标后,就加载该 Bean,否则不加载,所以接下来就行批改

代码革新

1、创立一个类实现 Condition 接口,重写 matches 办法,而后在办法外面写条件。返回 true 代表加载 user 对象的 bean,返回 false 示意不加载

import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;
public class ClassCondition implements Condition {
    @Override
    public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
      // 需要:如果 pom.xml 导入了 Jedis 坐标后,就加载该 User 对象的 Bean,否则不加载
        boolean flag=true;
        try {
            // 如果导入了 Jedis 坐标能够通过喷射的模式获取到 Jedis 对象。Class<?> clazz = Class.forName("redis.clients.jedis.Jedis");

        } catch (ClassNotFoundException e) {
           // 如果程序报错,证实没有导入 Jedis 坐标,所以获取不到
            flag=false;

        }
        return flag;
    }
}

2、在 UserConfig.java 类中创立 User 对象 Bean 的办法上加上 @Conditional(ClassCondition.class) 注解,注解外面传入要判断的条件实现类,依据该类的 matches 办法的返回值进行操作,返回 true 代表能够加载 User 对象的 bean,返回 false 示意不能够加载

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) // 退出条件判断的实现类,依据返回值判断是否要加载该 bean
    public User user(){return new User();
    }
}

4、测试

<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
</dependency>

你在 pom.xml 导入了下面的坐标,运行 springboot 的启动类,如果有就失常获取,如果没有程序就会报错,提醒找不到 user 的 bean

如果你在运行这个代码的过程中有遇到问题,请加小编 vi 信 xxf960513,!帮忙你疾速把握这个性能代码!

正文完
 0