SpringBoot使用AutoConfiguration自动配置Bean

当我们需要将我们的bean创建打包成jar给其他项目使用时,使用AutoConfiguration来创建bean是比较好的选择~

假设我们需要自动配置这样的类

java 复制代码
package local.my_sb4.autoconfigure;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 自定义服务类
 * 这是自动配置将要创建和管理的bean
 */
public class CustomService {
    private static final Logger logger = LoggerFactory.getLogger(CustomService.class);
    private final CustomServiceProperties properties;
    public CustomService(CustomServiceProperties properties) {
        this.properties = properties;
        logger.info("初始化自定义服务: {}", properties.getName());
    }
    /**
     * 执行业务操作
     * @param input 输入参数
     * @return 处理结果
     */
    public String process(String input) {
        logger.debug("处理输入: {}", input);
        
        if (!properties.isEnabled()) {
            logger.warn("服务已禁用");
            return "Service is disabled";
        }
        
        try {
            // 模拟业务处理
            String result = String.format("[%s] 处理结果: %s (超时: %dms, 重试: %d次)", 
                properties.getName(), input, properties.getTimeout(), properties.getMaxRetries());
            
            logger.info("处理完成: {}", result);
            return result;
            
        } catch (Exception e) {
            logger.error("处理失败", e);
            throw new RuntimeException("处理失败: " + e.getMessage(), e);
        }
    }
    /**
     * 获取服务信息
     * @return 服务信息
     */
    public String getServiceInfo() {
        return String.format("服务名称: %s, 描述: %s, 状态: %s", 
            properties.getName(), properties.getDescription(), properties.isEnabled() ? "启用" : "禁用");
    }
    /**
     * 健康检查
     * @return 健康状态
     */
    public boolean isHealthy() {
        return properties.isEnabled();
    }
}

首先我们需要引入支持自动配置的的依赖

plain 复制代码
dependencies {
        // ...其他依赖
	// 添加自动配置相关依赖
	annotationProcessor 'org.springframework.boot:spring-boot-configuration-processor'
	implementation 'org.springframework.boot:spring-boot-autoconfigure'
}

我们希望我们的想配置的类有自己的Properties类

java 复制代码
package local.my_sb4.autoconfigure;

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

/**
 * 自定义自动配置属性类
 * 用于配置自定义服务的行为
 */
@ConfigurationProperties(prefix = "custom.service")
public class CustomServiceProperties {
    /**
     * 是否启用自定义服务
     */
    public boolean enabled = true;
    /**
     * 服务名称
     */
    public String name = "default-service";
    /**
     * 服务描述
     */
    public String description = "自定义自动配置服务";
    /**
     * 超时时间(毫秒)
     */
    public long timeout = 5000;
    /**
     * 最大重试次数
     */
    public int maxRetries = 3;
}

现在开始编写我们的自动配置类

  1. 它要被@AutoConfiguration修饰
  2. 如果希望被配置的类存在时才配置,那么需要使用@ConditionalOnClass(目标类.class)来修饰
  3. 如果希望使用自己恶配置类,则需要@EnableConfigurationProperties(配置类.class)来修饰
  4. 如果希望某个配置参数为特定的值或为空时才进行配置,那么需要@ConditionalOnProperty(prefix = "参数名称前缀", name = "参数名称", havingValue = "特定值", matchIfMissing = true)

然后,我们的自动配置类是这样的

java 复制代码
package local.my_sb4.autoconfigure;

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

/**
 * 自定义服务自动配置类
 * 这是Spring Boot自动配置的核心类
 */
@AutoConfiguration //表示这是一个自动配置类
@ConditionalOnClass(CustomService.class) //当类路径下存在CustomService时才加载
@EnableConfigurationProperties(CustomServiceProperties.class) //启用自定义服务配置属性
@ConditionalOnProperty(prefix = "custom.service", name = "enabled", havingValue = "true", matchIfMissing = true) //当配置项custom.service.enabled=true或空时加载
public class CustomServiceAutoConfiguration {
    /**
     * 创建自定义服务Bean
     * 当容器中不存在CustomService类型的Bean时才会创建
     * 
     * @param properties 配置属性
     * @return 自定义服务实例
     */
    @Bean
    @ConditionalOnMissingBean
    public CustomService customService(CustomServiceProperties properties) {
        return new CustomService(properties);
    }
}

如果需要启用自动配置,还需要编辑*.imports文件以让spring找到我们的自动配置类

resources/META-INF/spring/目录创建org.springframework.boot.autoconfigure.AutoConfiguration.imports文件;

文件的内容是通过换行分隔的自动配置类全限定名称local.my_sb4.autoconfigure.CustomServiceAutoConfiguration

现在开始使用这个自动配置

假设引用我们自动配置的项目这样配置了参数

properties 复制代码
# 自定义服务配置
custom.service.enabled=true
custom.service.name=my-custom-service
custom.service.description=我的自定义自动配置服务
custom.service.timeout=10000
custom.service.max-retries=5

启动应用将会打印

plain 复制代码
2025-12-15T14:55:46.207+08:00  INFO 77305 --- [my_sb4] [           main] l.my_sb4.autoconfigure.CustomService     : 初始化自定义服务: default-service

说明我们的自动配置成功了~

现在编写一个controller来使用我们自动配置的类

java 复制代码
package local.my_sb4.controller;

import local.my_sb4.autoconfigure.CustomService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * 自定义服务测试控制器
 * 用于测试自定义自动配置是否生效
 */
@RestController
@RequestMapping("/api/custom")
public class CustomServiceController {
    @Autowired
    private CustomService customService;
    /**
     * 测试自定义服务
     * @param input 输入参数
     * @return 处理结果
     */
    @GetMapping("/process")
    public String process(@RequestParam(value = "input", defaultValue = "测试输入") String input) {
        return customService.process(input);
    }
    /**
     * 获取服务信息
     * @return 服务信息
     */
    @GetMapping("/info")
    public String getServiceInfo() {
        return customService.getServiceInfo();
    }
    /**
     * 健康检查
     * @return 健康状态
     */
    @GetMapping("/health")
    public String healthCheck() {
        boolean isHealthy = customService.isHealthy();
        return "{\"status\": \"" + (isHealthy ? "UP" : "DOWN") + "\"}";
    }
}

我们来测试下

启动应用,通过curl来测试

shell 复制代码
fqy@fqyPC my_sb4 % curl "http://127.0.0.1:8080/api/custom/process?input=test"
[default-service] 处理结果: test (超时: 5000ms, 重试: 3次)%                                                                                                                                                                                                                        fqy@fqyPC my_sb4 % curl localhost:8080/api/custom/info
服务名称: default-service, 描述: 自定义自动配置服务, 状态: 启用%                                                                                                                                                                                                                   fqy@fqyPC my_sb4 % curl localhost:8080/api/custom/health
{"status": "UP"}% 

测试结果符合我们的预期~

相关推荐
钰衡大师1 小时前
Activiti 7 工作流技术文档
java·数据库·spring boot
Ruci ALYS1 小时前
SpringBoot Maven快速上手
spring boot·后端·maven
rADu REME2 小时前
SpringBoot + vue 管理系统
vue.js·spring boot·后端
你好潘先生2 小时前
Next.js + Spring Boot 实现 AI 多模型并行对话系统(架构设计与关键实现)
spring boot·向量检索·next.js·pgvector·ai对话·多模型对比·sse流式输出
苍煜2 小时前
SpringBoot单体应用到分布式下的数据库锁、事务、Redis事务、分布式锁、分布式事务协调
数据库·spring boot·分布式
Dylan的码园2 小时前
springBoot与Web后端基础
前端·spring boot·后端
skiy3 小时前
SpringBoot项目中读取resource目录下的文件(六种方法)
spring boot·python·pycharm
salipopl3 小时前
Spring Boot 整合 Druid 并开启监控
java·spring boot·后端
geNE GENT3 小时前
Spring Boot 实战篇(四):实现用户登录与注册功能
java·spring boot·后端
HackTorjan13 小时前
深度神经网络的反向传播与梯度优化原理
人工智能·spring boot·神经网络·机器学习·dnn