SpringBoot自动装配原理---Spring

自动装配原理

SpringBoot自动装配原理---Spring_第1张图片

在 SpringBoot 项目的启动类上有一个 @SpringBootApplication 注解,这个注解是对三个注解进行了封装。
自动化配置机制中​核心注解:@EnableAutoConfiguration

@EnableAutoConfiguration

SpringBoot自动装配原理---Spring_第2张图片

  • 通过 @Import 导入AutoConfigurationImportSelector配置选择器
  • 扫描以下路径的配置文件:
    • 项目自身的META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports
    • 项目自身以及依赖JAR包的META-INF/spring.factories(旧版)
  • ​条件装载:配置类中定义的Bean会根据条件注解决定是否注册到Spring容器

实现自定义类的自动配置

1. 创建自动配置类

package com.example.autoconfig;

import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;

@AutoConfiguration
@ConditionalOnClass(MyService.class) // 当类路径中存在MyService时加载
@EnableConfigurationProperties(MyServiceProperties.class) // 启用配置属性
public class MyServiceAutoConfiguration {

    @Bean
    @ConditionalOnMissingBean // 当容器中不存在该Bean时创建
    public MyService myService(MyServiceProperties properties) {
        return new MyService(properties.getPrefix(), properties.getSuffix());
    }
}

2. 创建配置属性类

package com.example.autoconfig;

import org.springframework.boot.context.properties.ConfigurationProperties;

@ConfigurationProperties(prefix = "my.service")
public class MyServiceProperties {
    private String prefix = "Hello";
    private String suffix = "!";

    // getters and setters
    public String getPrefix() {
        return prefix;
    }

    public void setPrefix(String prefix) {
        this.prefix = prefix;
    }

    public String getSuffix() {
        return suffix;
    }

    public void setSuffix(String suffix) {
        this.suffix = suffix;
    }
}

3. 创建自定义服务类

package com.example.autoconfig;

public class MyService {
    private final String prefix;
    private final String suffix;

    public MyService(String prefix, String suffix) {
        this.prefix = prefix;
        this.suffix = suffix;
    }

    public String greet(String name) {
        return prefix + " " + name + suffix;
    }
}

4. 注册自动配置类

在 src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports 文件中添加:
com.example.autoconfig.MyServiceAutoConfiguration

5. 使用自动配置

只需将上述项目使用 maven 打成 jar 包,在其他项目中添加依赖并配置属性即可使用,这就是标准 Starter 方式:

# application.yml
my:
  service:
    prefix: "Hi"
    suffix: "!!!"
@Service
public class SomeService {
    private final MyService myService;
    
    public SomeService(MyService myService) {
        this.myService = myService;
    }
    
    public void doSomething() {
        System.out.println(myService.greet("World"));
    }
}

你可能感兴趣的:(#,Spring,spring,spring,boot,后端)