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

六、样例源码

https://gitee.com/HaiShangShengMingYue/mock-spring-boot-starter.git

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值