手写springboot starter

starter会把所有用到的依赖都给包含进来,避免了开发者自己去引入依赖所带来的麻烦。

虽然不同的starter实现起来各有差异,但是他们基本上都会使用到两个相同的内容:ConfigurationProperties和AutoConfiguration。

Starters 是一组可以让你很方便在应用增加的依赖关系描述符的集合。或者可以这样理解,平时我们开发的时候很多情况下都会有一个模块依赖另一个模块,这个时候我们一般都是采用 maven 的模块依赖,进行模块的依赖

pom 依赖

 

 1 MyJsonAutoConfiguration

    package com.gupao.starter.demo.service;

    import org.springframework.beans.factory.annotation.Autowired;

    import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;

    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

    @ConditionalOnClass(MyJsonService.class)

    @EnableConfigurationProperties(MyJsonProperties.class)

    public class MyJsonAutoConfiguration {

        @Autowired

        private MyJsonProperties myJsonProperties;

        @Bean

        @ConditionalOnMissingBean(MyJsonService.class)

        public MyJsonService myJsonService() {

        MyJsonService myJsonService = new MyJsonService();

        myJsonService.setName(myJsonProperties.getName());

        return myJsonService;

    }

}

2  MyJsonProperties

package com.gupao.starter.demo.service;

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

@ConfigurationProperties(prefix ="gp.json")

public class MyJsonProperties {

    public static final String DEFAULT_NAME = "gp";

    private String name = DEFAULT_NAME;

    public String getName() {

        return name;

    }

    public void setName(String name) {

        this.name = name;

    }

}

3 MyJsonService

package com.gupao.starter.demo.service;

import com.alibaba.fastjson.JSON;

public class MyJsonService {

    private String name;

    public String objToJson(Object obj) {

        return getName() + JSON.toJSONString(obj);

    }

    public String getName() {

        return name;

    }

   public void setName(String name) {

       this.name = name;

    }

}

自动装配

    然后我们通过运行mvn install命令,将这个项目打包成 jar 部署到本地仓库中,提供让另一个服务调用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值