springboot笔记七自定义场景启动器starter

Posted 今夜月色很美

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了springboot笔记七自定义场景启动器starter相关的知识,希望对你有一定的参考价值。

一、创建场景启动器项目

1.创建一个空project

2.在空project中添加maven模块mock-spring-boot-starter

3.在空project中添加spring Initialirz模块mock-spring-boot-starter-autoconfigure

4.在mock-spring-boot-starter添加自动配置依赖mock-spring-boot-starter-autoconfigure

5.移除mock-spring-boot-starter-autoconfigure默认依赖模块spring-boot-starter-test和插件,删除启动类和配置文件

二、编写HelloService

package com.mock.autoconfigure.service;

import com.mock.autoconfigure.properties.MockProperties;
import org.springframework.beans.factory.annotation.Autowired;

public class HelloService {
    @Autowired
    private MockProperties mockProperties;

    public void sayHello(){
        System.out.println(mockProperties.getUrl() + "===" + mockProperties.getIp());
    }
}

编写配置文件属性绑定类

package com.mock.autoconfigure.properties;

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

@ConfigurationProperties("mock.npu")
public class MockProperties {
    private String ip;
    private String url;

    public String getIp() {
        return ip;
    }

    public void setIp(String ip) {
        this.ip = ip;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }
}

三、编写自动注入类

package com.mock.autoconfigure;

import com.mock.autoconfigure.aspect.MockAspect;
import com.mock.autoconfigure.properties.MockProperties;
import com.mock.autoconfigure.service.HelloService;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableConfigurationProperties(MockProperties.class)
public class MockAutoConfiguration {
    @Bean
    public MockAspect mockAspect(){
        return new MockAspect();
    }

    @Bean
    public HelloService helloService(){
        return new HelloService();
    }
}

四、配置启动加载

在mock-spring-boot-starter-autoconfigure模块resources文件夹下创建META-INF/spring.factories文件

# EnableAutoConfiguration下面的类启动自动加载
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\\
com.mock.autoconfigure.MockAutoConfiguration

五、使用自定义starter

在项目中引入自定义starter的maven坐标,然后即可在项目中注入自定义starter注册的bean

以上是关于springboot笔记七自定义场景启动器starter的主要内容,如果未能解决你的问题,请参考以下文章

SpringBoot 学习笔记心得自定义Starter启动器

SpringBoot系列之自定义starter实践教程

SpringBoot - FileStorage Starter场景启动器

SpringBoot - FileStorage Starter场景启动器

Spring Boot笔记之自定义启动banner

spring boot可以自定义properties吗