首页 > 其他分享 >springboot-自己开发start

springboot-自己开发start

时间:2023-04-02 09:11:14浏览次数:34  
标签:springboot String cycleReset spring start 开发 IpProperties public cycle

步骤

命名规范

  • 第三方在建立自己的 Starter 的时候命名规则统一用xxx-spring-boot-starter,
  • 官方提供的 Starter 统一命名方式为spring-boot-starter-xxx。

步骤

  • 新建一个Maven项目,在pom.xml文件中定义好所需依赖;
  • 新建配置类,写好配置项和默认值,使用@ConfigurationProperties指明配置项前缀;
  • 新建自动装配类,使用@Configuration@Bean来进行自动装配;
  • 新建spring.factories文件,用于指定自动装配类的路径;
  • 将starter安装到maven仓库,让其他项目能够引用;
  • 需要提示功能的话,还必须有spring-configuration-metadata.json,通过依赖spring-boot-configuration-processor生成的,发布后一定要删除该依赖,否则会出双份的提示信息。

1、创建项目,写好依赖

  • 删除test依赖和包
  • spring-boot-configuration-processor 最后是要删除的。主要用于生成spring-configuration-metadata.json
<dependencies>
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-web</artifactId>
	</dependency>
</dependencies>

2、属性配置类

  • 写好配置项和默认值。并使用@ConfigurationProperties指明配置项前缀,用于加载配置文件对应的前缀配置项:
  • 建议写doc文档,这样在配置时会有提示
  • 如果仅仅添加@ConfigurationProperties,会有报错提示,因为有这个注解,他必须是一个可被管控的bean,先不用管,在IpAutoConfiguration中引入@Import(IpProperties.class)就不会再报错了
  • @Component("ipProperties")可以不用写,但是服务类上使用了别名,这里主要的目的是定义IpProperties的别名

public enum IpModeEnum {
    /**
     * 极简信息
     */
    SIMPLE("simple"),
    /**
     * 详细信息
     */
    DETAIL("detail");
    private final String value;

    IpModeEnum(String value) {
        this.value = value;
    }

    public String getValue() {
        return value;
    }
}


@Component("ipProperties")
@ConfigurationProperties(prefix = "tools.ip")
public class IpProperties {
    /**
     * 日志显示周期
     */
    private Integer cycle = 5;
    /**
     * 是否周期内重置数据
     */
    private boolean cycleReset = false;
    /**
     * 日志输出模式  detail:详细模式  simple:极简模式
     */
    private String model = IpModeEnum.DETAIL.getValue();

    public IpProperties() {
    }

    public IpProperties(Integer cycle, boolean cycleReset, String model) {
        this.cycle = cycle;
        this.cycleReset = cycleReset;
        this.model = model;
    }

    /**
     * 获取
     * @return cycle
     */
    public Integer getCycle() {
        return cycle;
    }

    /**
     * 设置
     * @param cycle
     */
    public void setCycle(Integer cycle) {
        this.cycle = cycle;
    }

    /**
     * 获取
     * @return cycleReset
     */
    public boolean isCycleReset() {
        return cycleReset;
    }

    /**
     * 设置
     * @param cycleReset
     */
    public void setCycleReset(boolean cycleReset) {
        this.cycleReset = cycleReset;
    }

    /**
     * 获取
     * @return model
     */
    public String getModel() {
        return model;
    }

    /**
     * 设置
     * @param model
     */
    public void setModel(String model) {
        this.model = model;
    }

    public String toString() {
        return "IpProperties{cycle = " + cycle + ", cycleReset = " + cycleReset + ", model = " + model + "}";
    }
}

3、服务类

public class IpCountService {
    /**
     * 统计的集合
     */
    private final Map<String,Integer> ipCountMap = new HashMap<>();
    /**
     * 当前的request对象的注入工作由使用当前starter的工程提供自动装配
     */
    @Resource
    private HttpServletRequest httpServletRequest;
    @Autowired
    private IpProperties ipProperties;
    /**
     * 每次调用当前操作,就记录当前访问的IP,然后累加访问次数,并把数据放到map中
     */
    public void count(){
        //1.获取当前操作的IP地址
        String ip = httpServletRequest.getRemoteAddr();
        //2.根据IP地址从Map取值,并递增
        ipCountMap.merge(ip, 1, Integer::sum);
    }
    @Scheduled(cron = "0/#{ipProperties.cycle} * * * * ?")
    public void print(){

        if(ipProperties.getMode().equals(LogModeEnum.DETAIL.getValue())){
            System.out.println("         IP访问监控");
            System.out.println("+-----ip-address-----+--num--+");
            for (Map.Entry<String, Integer> entry : ipCountMap.entrySet()) {
                String key = entry.getKey();
                Integer value = entry.getValue();
                System.out.printf("|%18s  |%5d  |%n",key,value);
            }
            System.out.println("+--------------------+-------+");
        }else if(ipProperties.getMode().equals(LogModeEnum.SIMPLE.getValue())){
            System.out.println("     IP访问监控");
            System.out.println("+-----ip-address-----+");
            for (String key: ipCountMap.keySet()) {
                System.out.printf("|%18s  |%n",key);
            }
            System.out.println("+--------------------+");
        }

        if(ipProperties.isCycleReset()){
            ipCountMap.clear();
        }
    }
}

3、自动配置类

  • EnableScheduling:开启定时任务
@EnableScheduling
@Import(IpProperties.class)
public class IpAutoConfiguration {
    @Bean
    public IpCountService  ipCountService(){
        return new IpCountService();
    }
}

4、拦截器

public class IpCountInterceptor implements HandlerInterceptor {

    @Autowired
    private IpCountService ipCountService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        ipCountService.count();
        return true;
    }
}


@Configuration
public class SpringMvcConfig implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(ipCountInterceptor()).addPathPatterns("/**");
    }

    @Bean
    public IpCountInterceptor ipCountInterceptor(){
        return new IpCountInterceptor();
    }

}

5、新建spring.factories文件,用于指定自动装配类的路径;

  • 路径:src/main/resources/META-INF/spring.factories
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
cn.tjhis.ipconfig.config.IpAutoConfiguration

6、新建spring-configuration-metadata.json文件,用于在配置时自动提示;

{
  "groups": [
    {
      "name": "tools.ip",
      "type": "cn.tjhis.ipconfig.config.IpProperties",
      "sourceType": "cn.tjhis.ipconfig.config.IpProperties"
    }
  ],
  "properties": [
    {
      "name": "tools.ip.cycle",
      "type": "java.lang.Integer",
      "description": "日志显示周期",
      "sourceType": "cn.tjhis.ipconfig.config.IpProperties",
      "defaultValue": 5
    },
    {
      "name": "tools.ip.cycle-reset",
      "type": "java.lang.Boolean",
      "description": "是否周期内重置数据",
      "sourceType": "cn.tjhis.ipconfig.config.IpProperties",
      "defaultValue": false
    },
    {
      "name": "tools.ip.mode",
      "type": "java.lang.String",
      "description": "日志输出模式  detail:详细模式  simple:极简模式",
      "sourceType": "cn.tjhis.ipconfig.config.IpProperties"
    }
  ],
  "hints": [
    {
      "name": "tools.ip.mode",
      "values": [
        {
          "value": "detail",
          "description": "详细模式."
        },
        {
          "value": "simple",
          "description": "极简模式."
        }
      ]
    }
  ]
}

6、把其安装到maven仓库,这样其他工程就可以引用了

  • clean
  • install

7、在另一个web工程中引入

<dependency>
	<groupId>cn.tjhis</groupId>
	<artifactId>ipCount-spring-boot-starter</artifactId>
	<version>1.0.1</version>
</dependency>

标签:springboot,String,cycleReset,spring,start,开发,IpProperties,public,cycle
From: https://www.cnblogs.com/his365/p/17279882.html

相关文章

  • 《U8开发听我说》第一讲:UAP报表查询过滤条件如何设置枚举
    《U8开发听我说》专栏,查看文章清单请点击知识点科普:什么是过滤控件?过滤控件是U8应用程序常用的控件之一,广泛用于报表、单据列表等场景中,它有以下特性:分设计时和运行时,设计时是集成在UAP中。提供程序员编程的接口。提供回调接口。对象不销毁则保留用户的各种设置。通过常用......
  • 【SpringBoot】关闭SpringBoot启动图标(banner)
    SpringBoot启动的时候会有如下图标如果想去掉此图标在配置文件添加一下内容配置文件:application.yml添加内容:spring:main:banner-mode:off#关闭SpringBoot启动图标(banner) ......
  • 常用注解-SpringBoot请求
    SpringBoot请求常用注解及作用范围:@Controller:【类】需要返回一个视图(themleaf),加注解4@ResponseBody等于注解2@RestController:【类】返回字符串等,与注解1都属于控制器,@RequestMapping:【方法/类】设置方法或者类的请求地址,@ResponseBody:【方法】支持将返回值放在response......
  • OpenGL Mac开发-如何使用imgui(1.89.4)插件进行调试
    为了调试我们的OpenGLDemo,可以尝试使用一个成熟的开源GUI插件imgui。1,首先进入imgui在github上的地址。在Release中下载最近的版本,可以得到一个Zip压缩包。现在是2023年的4月1日,我下载到的版本是1.89.4,与Cherno的OpenGL教程中的代码略微有些区别。如果你看的是Cherno的教程,也......
  • SpringBoot进阶教程(七十五)数据脱敏
    无论对于什么业务来说,用户数据信息的安全性无疑都是非常重要的。尤其是在数字经济大火背景下,数据的安全性就显得更加重要。数据脱敏可以分为两个部分,一个是DB层面,防止DB数据泄露,暴露用户信息;一个是接口层面,有些UI展示需要数据脱敏,防止用户信息被人刷走了。v需求背景DB层面的......
  • 开发一个二方包,优雅地为系统接入ELK(elasticsearch+logstash+kibana)
    去年公司由于不断发展,内部自研系统越来越多,所以后来搭建了一个日志收集平台,并将日志收集功能以二方包形式引入各个自研系统,避免每个自研系统都要建立一套自己的日志模块,节约了开发时间,管理起来也更加容易。这篇文章主要介绍如何编写二方包,并整合到各个系统中。先介绍整个ELK日志......
  • 盲盒商城功能讲解,盲盒商城软件开发
    盲盒商城app有哪些,盲盒商城小程序有哪些,盲盒商城软件开发多少钱,盲盒商城软件开发公司哪家好,类似魔点APP开发,类似魔点APP开发多少钱,类似魔点软件OEM开发,盲盒商城软件开发,盲盒商城小程序开发,盲盒商城app开发,盲盒商城平台搭建随着科技的不断发展,越来越多的人开始使用智能手机,......
  • java开发技术栈如何选型
    前言   2023泰山景区门票免费政策是从1月21日到3月31,今天4.1起不再免费啦,泰山的人、山和系统终于平安的渡劫过去!   洪峰时疯狂的抢票、各类攻击,分销MT两次凌晨抗洪事件,我及其我的团队又一次得到历练。 此处插个广告,有需要景区票务系统的可联系我,业务推荐有重礼!  ......
  • SpringBoot项目启动时初始化操作方式
    1.实现InitializingBean重写afterPropertiesSet()方法。@Component@Slf4jpublicclassInitOneTestimplementsInitializingBean{@OverridepublicvoidafterPropertiesSet()throwsException{log.info("InitOneTestinitsuccess");}}2......
  • Python Web简历网站开发
    1.搭建环境: -安装Python、Django、Vue开发环境2.配置环境: -配置Django项目架构,安装并配置Vue-cli以便使用Vue来实现前端功能3.页面设计: -主页面:包含网站首页、用户登录注册、管理中心等功能 -用户简历页面:提供简历创建、简历修改、简历分享等功能 -搜......