SpringBoot自定义一个starter

 

 

 

 

 

一个项目下创建两个模块

 

 

 

在hello-springboot-starter的项目pom.xml引入hello-springboot-starter-autoconfigure的依赖  其他什么都不需要写

 

 

 

hello-springboot-starter-autoconfigure的pom依赖根据自己需要的来

 

 

 

 

项目结构

 

 

 

 

HelloProperties.java    读取配置文件的配置

复制代码
import org.springframework.boot.context.properties.ConfigurationProperties;

@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;
    }
}
复制代码

 

HelloService.java   主要业务实现逻辑类

复制代码
import com.yvioo.hello.config.HelloProperties;

import javax.annotation.Resource;

/**
 * 默认不要放在容器中
 */
public class HelloService {

    @Resource
    private HelloProperties helloProperties;

    public String sayHello(String userName){
        return helloProperties.getPrefix()+":"+userName+"》》"+helloProperties.getSuffix();
    }
}
复制代码

 

 

HelloServiceAutoConfiguration.java

复制代码
import com.yvioo.hello.config.HelloProperties;
import com.yvioo.hello.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
@EnableConfigurationProperties(HelloProperties.class) //默认HelloProperties放在容器中
public class HelloServiceAutoConfiguration {

    @Bean
    @ConditionalOnMissingBean(HelloService.class)  //容器中不存在 HelloService 执行这个方法
    public HelloService helloService(){
        HelloService helloService=new HelloService();
        return helloService;
    }
}
复制代码

 

 

META-INF/spring.factories.   写自动配置类的路径,会自动加载

# Auto Configure
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.yvioo.hello.auto.HelloServiceAutoConfiguration

 

 

使用

引入hello-springboot-starter的依赖

 

 

 

 

 

 

posted @   yvioo  阅读(8)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2020-09-20 查找MySql的配置文件my.cnf所在路径
点击右上角即可分享
微信分享提示