SpringBoot的自动装配原理

本文介绍了SpringBoot中的自动装配机制,展示了如何不使用XML配置就能将Bean注入到IOC容器中。并通过实例说明了如何配置Redis数据源并创建Controller类进行数据操作。

在Spring Boot中有一个点叫自动装配是Starter的基础,也是整个Spring Boot的核心,那什么是自动装配呢?简单来说,就是自动将Bean装配到IOC容器中这么一个操作。

 一、Spring Boot中的自动装配

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

配置Redis数据源

spring.redis.host=localhost
spring.redis.port=6379

 创建一个Controller

@RestController
public class Controller {

    @Autowired
    RedisTemplate redisTemplate;

    @GetMapping("/show")
    public String show(){
        redisTemplate.opsForValue().set("hello","Spring Boot");
        return "成功";
    }
}

这就是一个Spring Boot的装配机制,没有通过xml的方式注入到容器中,但是在Controller中可以直接通过@Autowired来直接注入使用。

 二、自动装配是如何实现的?

@SpringBootApplication
public class TestDemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(TestDemoApplication.class, args);
    }
}

@SpringBootApplication 注解主要由三个注解组成:@ComponentScan、@SpringBootConfiguration、@EnableAutoConfiguration

@SpringBootConfiguration:这个注解的底层是一个@Configuration注解,意思被@Configuration注解修饰的类是一个IOC容器,支持JavaConfig的方式来进行配置;

@ComponentScan:这个就是扫描注解的意思,默认扫描当前类所在的包及其子包下包含的注解,将@Controller/@Service/@Component/@Repository等注解加载到IOC容器中;

@EnableAutoConfiguration:这个注解表明启动自动装配,里面包含连个比较重要的注解@AutoConfigurationPackage和@Import。

可点击@SpringBootApplication注解进入源码查看

@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(
    excludeFilters = {@Filter(
    type = FilterType.CUSTOM,
    classes = {TypeExcludeFilter.class}
), @Filter(
    type = FilterType.CUSTOM,
    classes = {AutoConfigurationExcludeFilter.class}
)}
)
public @interface SpringBootApplication {

}

再继续点进去 @EnableAutoConfiguration 注解

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage // 把使用了该注解的类所在的包及子包下所有组件扫描到Spring IOC容器中
@Import({AutoConfigurationImportSelector.class})
public @interface EnableAutoConfiguration {
    String ENABLED_OVERRIDE_PROPERTY = "spring.boot.enableautoconfiguration";

    Class<?>[] exclude() default {};

    String[] excludeName() default {};
}

@EnableAutoConfiguration注解又使用了@Import注解,@Import注解是Spring提供用来给IOC导入Bean的一种方式,这里导入了一个类名称为AutoConfigurationImportSelector的Bean,从名字来看这个类的功能似乎是用来完成自动装配导入工作 

 public String[] selectImports(AnnotationMetadata annotationMetadata) {
        if (!this.isEnabled(annotationMetadata)) {
            return NO_IMPORTS;
        } else {
            AutoConfigurationImportSelector.AutoConfigurationEntry autoConfigurationEntry = this.getAutoConfigurationEntry(annotationMetadata);
            return StringUtils.toStringArray(autoConfigurationEntry.getConfigurations());
        }
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值