Spring-Boot中有很多Enable开头的注解,通过添加注解来开启一项功能,如

其原理是什么?如何开发自己的Enable注解?

1.原理

以@EnableScheduling为例,查看其源码,发现添加了一个@Import注解

继续查看@Import注解源码,发现其是由Spring提供的,用来导入配置类的,在配置类中定义的Bean(@Bean),可通过@Autowired注入到容器中,也就是可以被扫描到

2.自定义

了解了Enable注解的原理,我们就可以开发自己的Enable注解了,下面的例子实现了通过@Enable注解方式开启服务器负载监控的功能

2.1 定义定时任务类

package com.yc.dudu.common.monitor;

import com.alibaba.fastjson.JSONObject;
import com.sun.management.OperatingSystemMXBean;
import com.yc.dudu.common.constant.CommonConstants;
import com.yc.dudu.common.util.DateTimeUtil;
import com.yc.dudu.common.vo.ServerMonitorInfo;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled; import java.io.File;
import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.net.UnknownHostException; /**
* 收集服务器负载信息
*
* @author zhya
* @date 2018/9/20
**/
@Slf4j
@EnableScheduling
public class ServerLoadMonitorRunner implements CommandLineRunner {
/**
* 自定义log,输出服务器负载信息到日志文件
*/
private static final Logger monitorLog = LoggerFactory.getLogger("serverMonitorLog"); /**
* 系统信息
*/
private static final OperatingSystemMXBean mem = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean(); /**
* 收集服务器负载信息并输出到日志文件
*/
@Scheduled(cron = "*/5 * * * * ?")
public void collectServerSystemLoad() {
try {
// 输出json格式的信息到文件
monitorLog.info(JSONObject.toJSONString(new ServerMonitorInfo(InetAddress.getLocalHost().getHostName(),
String.valueOf(mem.getFreePhysicalMemorySize() / CommonConstants.BYTES_TO_MB),
String.valueOf(mem.getSystemCpuLoad()),
String.valueOf(File.listRoots()[0].getFreeSpace() / CommonConstants.BYTES_TO_MB),
DateTimeUtil.getNowDateTimeStr())));
} catch (UnknownHostException e) {
log.error(e.getMessage());
}
} /**
* Callback used to run the bean.
*
* @param args incoming main method arguments
* @throws Exception on error
*/
@Override
public void run(String... args) throws Exception {
try {
collectServerSystemLoad();
} catch (Exception e) {
log.error(e.getMessage());
// 不做处理,继续运行
}
}
}

  

2.2 定义配置类,其中声明定时任务Bean

package com.yc.dudu.common.monitor;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import javax.annotation.PostConstruct; /**
* 服务器负载监控自动配置类
*
* @author zhya
* @date 2018/09/20
**/
@Configuration
public class ServerLoadMonitorAutoConfig {
/**
* 是否开启监控配置参数
*/
@Value("${monitor.server.enabled:}")
private String enabledConfig; /**
* 错误提醒
*/
@PostConstruct
protected void init() {
if (StringUtils.isBlank(enabledConfig)) {
System.err.println("~~~Please config the monitor.server.enabled property in application.yml file to enable server monitor function~~~");
}
} /**
* 根据运行环境决定是否开启服务器负载信息监控
*
* @return
*/
@Bean
@ConditionalOnProperty(prefix = "monitor.server", name = "enabled", havingValue = "true")
protected ServerLoadMonitorRunner startServerMonitor() {
return new ServerLoadMonitorRunner();
}
}

2.3 定义自己的Enable注解,Import 配置类

package com.yc.dudu.common.monitor;

import org.springframework.context.annotation.Import;

import java.lang.annotation.*;

/**
* 服务器负载监控开启注解
*
* @author zhya
* @date 2018/09/20
**/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Import(ServerLoadMonitorAutoConfig.class)
@Documented
@Inherited
public @interface EnableServerLoadMonitor {
}

2.4 使用自定义的EnableServerLoadMonitor注解,配合着配置参数,就可以开启服务器负载监控功能了

package com.yc.dudu.gate.admin;

import com.yc.dudu.auth.client.EnableDuduAuthClient;
import com.yc.dudu.common.monitor.EnableServerLoadMonitor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.hystrix.EnableHystrix;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import zipkin2.Span;
import zipkin2.reporter.Reporter; /**
* admin网关启动类
*
* @author zhya
* @date 2018/9/20
**/
@EnableHystrix
@EnableServerLoadMonitor
@SpringBootApplication
@EnableDiscoveryClient
@EnableDuduAuthClient
@EnableFeignClients({"com.yc.dudu.auth.client.feign", "com.yc.dudu.gate.admin.feign"})
public class AdminGatewayApplication {
public static void main(String[] args) {
SpringApplication.run(AdminGatewayApplication.class, args);
System.out.println("AdminGatewayApplication is started!~~~~~~~~");
} /**
* 链路跟踪信息输出log
*/
private static Logger sleuthLog = LoggerFactory.getLogger("sleuthLog"); /**
* 将链路跟踪信息输出到日志文件
*
* @return
*/
@Bean
public Reporter<Span> spanReporter() {
Reporter<Span> reporter = span -> sleuthLog.info(span.toString());
return reporter;
}
}

  

自定义Spring-Boot @Enable注解的更多相关文章

  1. Spring Boot @Enable*注解源码解析及自定义@Enable*

      Spring Boot 一个重要的特点就是自动配置,约定大于配置,几乎所有组件使用其本身约定好的默认配置就可以使用,大大减轻配置的麻烦.其实现自动配置一个方式就是使用@Enable*注解,见其名知 ...

  2. 自定义spring boot starter 初尝试

    自定义简单spring boot starter 步骤 从几篇博客中了解了如何自定义starter,大概分为以下几个步骤: 1 引入相关依赖: 2 生成属性配置类: 3 生成核心服务类: 4 生成自动 ...

  3. Spring Boot常用注解总结

    Spring Boot常用注解总结 @RestController和@RequestMapping注解 @RestController注解,它继承自@Controller注解.4.0之前的版本,Spr ...

  4. Spring Boot 常用注解汇总

    一.启动注解 @SpringBootApplication @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documen ...

  5. 3个Spring Boot核心注解,你知道几个?

    Spring Boot 核心注解讲解 Spring Boot 最大的特点是无需 XML 配置文件,能自动扫描包路径装载并注入对象,并能做到根据 classpath 下的 jar 包自动配置. 所以 S ...

  6. Spring Boot@Component注解下的类无法@Autowired的问题

    title: Spring Boot@Component注解下的类无法@Autowired的问题 date: 2019-06-26 08:30:03 categories: Spring Boot t ...

  7. Spring boot 基于注解方式配置datasource

    Spring boot 基于注解方式配置datasource 编辑 ​ Xml配置 我们先来回顾下,使用xml配置数据源. 步骤: 先加载数据库相关配置文件; 配置数据源; 配置sqlSessionF ...

  8. 自定义spring boot的自动配置

    文章目录 添加Maven依赖 创建自定义 Auto-Configuration 添加Class Conditions 添加 bean Conditions Property Conditions Re ...

  9. 【SpringBoot】15. Spring Boot核心注解

    Spring Boot核心注解 1 @SpringBootApplication 代表是Spring Boot启动的类 2 @SpringBootConfiguration 通过bean对象来获取配置 ...

  10. spring boot纯注解开发模板

    简介 spring boot纯注解开发模板 创建项目 pom.xml导入所需依赖 点击查看源码 <dependencies> <dependency> <groupId& ...

随机推荐

  1. Summer training round2 #5 (Training #21)

    A:正着DFS一次处理出每个节点有多少个优先级比他低的(包括自己)作为值v[i] 求A B 再反着DFS求优先级比自己高的求C #include <bits/stdc++.h> #incl ...

  2. 用xshell连接l自己的inux

    有时候连接会提示失败(当然确保账号密码没错),这里需要安装一个服务,ssh服务器 1)ubuntu安装ssh服务器 sudo apt-get install openssh-server 2)出现问题 ...

  3. PM、RD、QA、OP、CM、EPG 英文缩写是什么意思?

    1.PM: Product Manager,产品经理,又称品牌经理.举凡产品从创意到上市,所有相关的研发.调研.生产.编预算.广告.促销活动等等,都由产品经理掌控. 2.RD: Research an ...

  4. GitHub : Hello World

    这个写的太好啦,让我也没啥可以写的啦:http://www.open-open.com/lib/view/open1454507333214.html

  5. CSS选择器的权重与优先规

    我们把特殊性分为4个等级,每个等级代表一类选择器,每个等级的值为其所代表的选择器的个数乘以这一等级的权值,最后把所有等级的值相加得出选择器的特殊值. 4个等级的定义如下: 第一等:代表内联样式,如: ...

  6. Python 文件I/O Ⅳ

    Python里的目录: 所有文件都包含在各个不同的目录下,不过Python也能轻松处理.os模块http://www.xuanhe.net/有许多方法能帮你创建,删除和更改目录. mkdir()方法 ...

  7. css设置元素垂直居中的几个方法

    最近有人问我怎么设置元素垂直居中?我....(这么基础的东西都不会?我有点说不出话来),  不过还是耐心的教了他几个方法,好吧教完他们,顺便把这些方法整理一下 第一种:通过设置成为表格元素的方式来实现 ...

  8. CGI环境变量

    所有的CGI程序都接收以下的环境变量,这些变量在CGI程序中发挥了重要的作用: 变量名 描述 CONTENT_TYPE 这个环境变量的值指示所传递来的信息的MIME类型.目前,环境变量CONTENT_ ...

  9. JSP大文件上传断点续传解决方案

    我们平时经常做的是上传文件,上传文件夹与上传文件类似,但也有一些不同之处,这次做了上传文件夹就记录下以备后用. 首先我们需要了解的是上传文件三要素: 1.表单提交方式:post (get方式提交有大小 ...

  10. TCP序列号和确认号

    TCP序列号和确认号详解 在网络分析中,读懂TCP序列号和确认号在的变化趋势,可以帮助我们学习TCP协议以及排查通讯故障,如通过查看序列号和确认号可以确定数据传输是否乱序.但我在查阅了当前很多资料后发 ...