MST
星途 面试题库

面试题:Java之Spring Boot自定义Starter基础

在Spring Boot中开发自定义Starter,简述自定义Starter的基本目录结构及关键配置文件的作用。
16.1万 热度难度
编程语言Java

知识考点

AI 面试

面试题答案

一键面试

基本目录结构

  1. 项目根目录:包含整个自定义Starter项目。
  2. src/main/java:存放Java源代码。通常有一个自动配置类,比如 XxxAutoConfiguration,用于自动配置相关功能。例如:
package com.example.demo;

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

@Configuration
@ConditionalOnClass(XxxService.class)
@EnableConfigurationProperties(XxxProperties.class)
public class XxxAutoConfiguration {

    private final XxxProperties properties;

    public XxxAutoConfiguration(XxxProperties properties) {
        this.properties = properties;
    }

    @Bean
    @ConditionalOnProperty(name = "xxx.enabled", havingValue = "true")
    public XxxService xxxService() {
        return new XxxService(properties.getSomeValue());
    }
}
  1. src/main/resources:存放资源文件。
    • META-INF/spring.factories:这是关键配置文件,用于指定自动配置类。格式如下:
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.example.demo.XxxAutoConfiguration
- 还可能包含 `application.properties` 等文件,用于存放默认配置属性,这些属性可以被 `XxxProperties` 类读取。例如:
xxx.some-value=defaultValue
  1. src/test/java:存放测试代码,用于对自定义Starter功能进行测试。

关键配置文件作用

  1. META-INF/spring.factories:Spring Boot在启动时会扫描该文件,根据其中配置的自动配置类,自动加载相关的配置。这样就实现了自定义Starter的自动配置功能,开发者在引入该Starter后,无需手动配置相关Bean等,Spring Boot自动完成配置。
  2. application.properties:定义了默认的配置属性值,这些值可以通过 XxxProperties 类绑定到配置类中,方便开发者在不修改代码的情况下,通过配置文件灵活调整Starter的行为。例如上述 xxx.some - value 属性,可以在引入Starter的项目的 application.properties 中被覆盖,以满足不同的需求。