1:创建maven项目
2:pom文件
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.ikeeper</groupId>
<artifactId>my-auto-bean-starter</artifactId>
<version>1.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>my-auto-bean-starter</name>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.7.RELEASE</version>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
</dependency>
</dependencies>
</project>
3:config
package com.ikeeper.config;
import com.ikeeper.properties.MyAutoProperties;
import com.ikeeper.service.DemoService;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@EnableConfigurationProperties({MyAutoProperties.class})
public class MyAutoBeanConfig {
@Bean
public DemoService demoService(MyAutoProperties myAutoProperties){
DemoService demoService = new DemoService();
demoService.setMyAutoProperties(myAutoProperties);
return demoService;
}
}
4.配置类
package com.ikeeper.properties;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties(prefix ="my.auto")
public class MyAutoProperties {
private int point;
public int getPoint() {
return point;
}
public void setPoint(int point) {
this.point = point;
}
}
5:service
package com.ikeeper.service;
import com.ikeeper.properties.MyAutoProperties;
public class DemoService {
private MyAutoProperties myAutoProperties;
public String hi(String name){
return "hello:"+name + "."+myAutoProperties.getPoint();
}
public void setMyAutoProperties(MyAutoProperties myAutoProperties) {
this.myAutoProperties = myAutoProperties;
}
}
6:META-INF/spring.factories
org.springframework.boot.autoconfigure.EnableAutoConfiguration = \
com.ikeeper.config.MyAutoBeanConfig
7:starter目录结构
8:其他应用业务代码pom依赖
<dependency>
<groupId>com.ikeeper</groupId>
<artifactId>my-auto-bean-starter</artifactId>
<version>1.0.1-SNAPSHOT</version>
</dependency>
9:业务配置
my.auto.point: 10
10:测试
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {AppMain.class})
public class SpringTest {
@Autowired
DemoService demoService;
@Test
public void hi(){
System.out.println(demoService.hi("henha"));
}
}