栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

自定义Spring Boot starter

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

自定义Spring Boot starter

文章目录
  • 自定义Spring Boot starter
    • 创建自动配置模块
    • 创建starter启动器
    • 新建Spring Boot工程使用

自定义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依赖


        
            org.springframework.boot
            spring-boot-starter-web
        

        
            org.springframework.boot
            spring-boot-starter-test
            test
        

        
            com.xl
            starter-spring-boot-stone
            1.0-SNAPSHOT
        
    

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/847465.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号