1、加入必要依赖
plugins {id 'java'id 'org.springframework.boot' version '3.2.6'id 'io.spring.dependency-management' version '1.1.5'
}
group 'org.example.test.starter'
version '1.1.0'jar{enabled=true// resolveMainClassName
}java {toolchain {languageVersion = JavaLanguageVersion.of(17)}
}repositories {maven { url 'https://maven.aliyun.com/repository/public/' }mavenCentral()
}dependencies {implementation 'org.springframework.boot:spring-boot-starter'implementation 'org.springframework.boot:spring-boot-configuration-processor'
}
2、定义Properties及业务service
@ConfigurationProperties(prefix = "test")
public class TestProperties {private List<String> dataList;private Map<String,String> dataMap;public List<String> getDataList() {return dataList;}public void setDataList(List<String> dataList) {this.dataList = dataList;}public Map<String, String> getDataMap() {return dataMap;}public void setDataMap(Map<String, String> dataMap) {this.dataMap = dataMap;}
}
public class TestConfigurationService {private List<String> list;public void showList(){list.forEach(System.out::println);}public void setList(List<String> list) {this.list = list;}
}
public class TestConfigurationService {private List<String> list;public void showList(){list.forEach(System.out::println);}public void setList(List<String> list) {this.list = list;}
}
@Component
public class TestImportService {@Resourceprivate TestProperties testProperties;public void showMap(){Map<String, String> dataMap = testProperties.getDataMap();if(!CollectionUtils.isEmpty(dataMap)){Set<String> keySet = dataMap.keySet();keySet.forEach(key-> System.out.println("key="+key+"--value="+dataMap.get(key)));}}}
3、自动配置类
@EnableConfigurationProperties({TestProperties.class})
@Import({TestImportService.class})
@Configuration
public class TestStarterAutoConfiguration {@Beanpublic TestConfigurationService testConfigurationService(TestProperties testProperties){TestConfigurationService testConfigurationService = new TestConfigurationService();testConfigurationService.setList(testProperties.getDataList());return testConfigurationService;}}
配置自动导入类,在resource创建META-INF/spring目录,在目录下创建org.springframework.boot.autoconfigure.AutoConfiguration.imports文件,写入TestStarterAutoConfiguration 全路径
4、调用测试
test:data-list:- Java- C/C++- C#- Vuedata-map:name: LiuPingage: 30address: HeNanXinXian
@Service
public class TestService {@Autowiredprivate TestConfigurationService testConfigurationService;@Autowiredprivate TestImportService testImportService;public void test(){testConfigurationService.showList();testImportService.showMap();}