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 小时前
SpringMVC + SpringBoot 核心知识点总结
java·spring boot·后端
郑洁文2 小时前
基于Spring Boot的流浪动物救助网站
java·spring boot·后端·毕设·流浪动物救助
指令集梦境4 小时前
Cursor + Spring Boot实战:从零写一个RESTful API
spring boot·后端·restful
普通网友6 小时前
springboot之集成Elasticsearch
spring boot·后端·elasticsearch
invicinble7 小时前
关于flowable流程引擎技术栈相关
spring boot
倒流时光三十年12 小时前
第十八章 搜索历史保存功能实现记录
spring boot·微信小程序
倒流时光三十年13 小时前
第十七章 投票页面增加搜索功能
spring boot·微信小程序
郑洁文13 小时前
基于Springboot的足球青训俱乐部管理系统的设计与实现
java·spring boot·后端·足球青训俱乐部管理系统
我登哥MVP14 小时前
Spring Boot 从“会用”到“精通”:自定义参数绑定原理
java·spring boot·后端·spring·servlet·maven·intellij-idea
小江的记录本14 小时前
【Spring全家桶】Spring AI核心原理、大模型集成、Prompt工程、RAG实现、AI Agent开发(附《思维导图》+《面试高频考点清单》)
java·人工智能·spring boot·后端·spring·面试·prompt