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 @ 2022-09-20 23:33  yvioo  阅读(7)  评论(0编辑  收藏  举报