0
点赞
收藏
分享

微信扫一扫

自定义Spring Boot starter

十日十月Freddie 2022-04-30 阅读 71

文章目录

自定义Spring Boot starter

创建自动配置模块

创建读取属性的类

package com.xl.stone.bean;

import org.springframework.boot.context.properties.ConfigurationProperties;

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

创建业务类

package com.xl.stone.service;

import com.xl.stone.bean.HelloProperties;
import org.springframework.beans.factory.annotation.Autowired;

public class HelloService {

    @Autowired
    HelloProperties helloProperties;

    public String sayHello(String username){
        return helloProperties.getPrefix() + ":"+username+"!"+helloProperties.getSuffix();
    }

}

创建自动装配配置类

package com.xl.stone.auto;

import com.xl.stone.bean.HelloProperties;
import com.xl.stone.service.HelloService;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@ConditionalOnMissingBean(HelloService.class)  //当容器内没有HelloService这个Bean时向容器内注入当前配置
@EnableConfigurationProperties({HelloProperties.class})
public class HelloAutoConfiguration {
    @Bean
    public HelloService helloService() {
        HelloService helloService = new HelloService();
        return helloService;
    }
}

创建META-INF/spring.factories文件,配置HelloAutoConfiguration的路径

在这里插入图片描述

创建starter启动器

只需在pom.xml中加入前一个自动配置工程的依赖即可

在这里插入图片描述

新建Spring Boot工程使用

在pom.xml加入starter依赖

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>com.xl</groupId>
            <artifactId>starter-spring-boot-stone</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
    </dependencies>

application.yml

stone:
  hello:
    prefix: 欢迎
    suffix: 拜拜

测试的controller

@RestController
public class TestController {

    @Autowired
    HelloService helloService;

    @GetMapping("/hello")
    public String sayHello(String username) {
        return helloService.sayHello(username);
    }

}	

启动后访问localhost:8080/hello?username=xhl

在这里插入图片描述

举报

相关推荐

0 条评论