pom.xml文件依赖如下:
<dependencies> <dependency> <groupId>com.yanxin</groupId> <artifactId>myhello-spring-boot-autoconfigurer</artifactId> <version>0.0.1-SNAPSHOT</version> </dependency> </dependencies>复制代码
第二个项目工程,自动配置包

pom.xml文件依赖如下:
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> </dependencies>复制代码

先考虑这样一个组件,这个组件中的方法需要调用另一个组件的某些属性,我们想springboot运行的时候会自动配置这个组件。利用组件来绑定属性,我们可以先写出这个类:
@ConfigurationProperties(prefix = "hello")public class HelloProperties { private String prefix; private String suffix; public String getPrefix() { return prefix; } public void setPrefix(String prefix) { this.prefix = prefix; } public String getSuffix() { return suffix; } public void setSuffix(String suffix) { this.suffix = suffix; }}复制代码
其中@ConfigurationProperties注解用来将配置文件的配置和类绑定起来。
我们需要的功能组件类如下:
public class HelloService { HelloProperties hello; public HelloProperties getHello() { return hello; } public void setHello(HelloProperties hello) { this.hello = hello; } public String sayHello(String name){ String reply = hello.getPrefix() + name + hello.getSuffix(); System.out.println(reply); return reply; }}复制代码
我们给HelloProperties属性加上setter和getter方法就是为了可以给功能组件注入HelloProperties属性值。
自动配置类如下:
@Configuration@ConditionalOnWebApplication@EnableConfigurationProperties(HelloProperties.class)public class HelloAutoConfiguration { @Autowired HelloProperties hello; @Bean public HelloService getService(){ HelloService ser = new HelloService(); ser.setHello(hello); return ser; }}复制代码
自动配置类有@Configuration注解,可以自动加载该类到容器中(那么,springboot程序何时加载HelloAutoConfiguration类呢?)
在/META-INF/spring.factories中配置好,以便读取自动配置类
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ com.yanxin.myhellospringbootautoconfigurer.HelloAutoConfiguration复制代码
将其导入maven仓库中,分别对两个module进行maven,install。
第三步,新建一个web项目,引用自定义starter新建test-starter module,pom.xml文件引入
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>com.yanxin</groupId> <artifactId>myhello-spring-boot-starter</artifactId> <version>1.0-SNAPSHOT</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency>