springboot 自定义一个简单的 starter

1.新建项目 。

启动器只用来做依赖导入;
专门来写一个自动配置模块;

idea 下建立空项目 hello-spring-boot-starter 添加两个子模块
spring-boot-starter-autoconfigurer,
spring-boot-starter-helloworld。
autoconfigurer 自动配置模块,

<!--引入starter的基本配置-->
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter</artifactId>
		</dependency>
	</dependencies>

helloworld,使用的模块,该模块使用autoconfigurer

 <dependencies>
        <dependency>
            <groupId>com.ccu.hello</groupId>
            <artifactId>spring-boot-starter-autoconfigurer</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>
    </dependencies>

2,需要一个配置类,配置类需要提供好装配好的类

加载的配置文件的类

@ConfigurationProperties(prefix = "atguigu.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;
    }
}

配置类 需纳入spring容器中

@Configuration
@ConditionalOnWebApplication //web应用才生效
@EnableConfigurationProperties(HelloProperties.class)
public class HelloServiceAutoConfiguration {
    @Autowired
    HelloProperties helloProperties;
    @Bean
    public HelloService helloService(){
        HelloService service = new HelloService();
        service.setHelloProperties(helloProperties);
        return service;  
    }
}

完成功能的类

public class HelloService {
    HelloProperties helloProperties;
    public HelloProperties getHelloProperties() {
        return helloProperties;
    }
    public void setHelloProperties(HelloProperties helloProperties) {
        this.helloProperties = helloProperties;
    }
    public String sayHellAtguigu(String name){
        return helloProperties.getPrefix()+"‐" +name + helloProperties.getSuffix();
    }
}

3自动装配(关键)

在classpath下:META-INF/spring.factories配置
org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.ccu.hello.springbootstarterautoconfigurer.HellloAutoConfiguration

最后使用idea maven 打包。

在新建一个项目导入依赖即可
在这里插入图片描述

加入properties.yml配置项

hello:
  prefix: xiaozi
  suffer:  nihaoqiang

定义controller访问

@Controller
public class HelloController {

    @Autowired
    private SayService sayService;

    @RequestMapping("/say/hello")
    @ResponseBody
    public String say(){
        return sayService.sayHello("haoren");
    }
}

最终效果

在这里插入图片描述

一个简单的starter 就完成了。

猜你喜欢

转载自blog.csdn.net/huang__2/article/details/82996305