Java 中待总结工具类学习(自定义注解,读取配置,字面List)
1、使用 MessageFormat 格式化文本
int planet = 7;
String event = "a disturbance in the Force"; String result = MessageFormat.format(
"At {1,time} on {1,date}, there was {2} on planet {0,number,integer}.",
planet, new Date(), event);
The output is:
At 12:30 PM on Jul 3, 2053, there was a disturbance in the Force on planet 7.
2、自定义注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface OperateLog { /**
* 模块名称
* @return
*/
String moudleName() default ""; /**
* 操作名称
* @return
*/
String optName() default ""; /**
* 业务类型描述
* @return
*/
String description() default ""; }
通过 aop 做拦截处理
@Aspect
@Component
public class OperateLogAspect { @Autowired
private OperateLogService operateLogService; @Pointcut("@annotation(com.youngcms.core.annotation.OperateLog)")
public void operateLogCut(){ } @Around("operateLogCut()")
public Object around(ProceedingJoinPoint point) throws Throwable {
long beginTime = System.currentTimeMillis();
//执行方法
Object result = point.proceed();
//执行时长(毫秒)
long time = System.currentTimeMillis() - beginTime;
//保存日志
saveOperateLog(point, time); return result;
} private void saveOperateLog(ProceedingJoinPoint joinPoint, long time) {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
RequestMapping classRequestMapping=method.getDeclaringClass().getAnnotation(RequestMapping.class);
OperateLog operateLog=method.getAnnotation(OperateLog.class);
RequestMapping mothodRequestMapping= method.getAnnotation(RequestMapping.class);
com.youngcms.bean.OperateLog operateLogBean=new com.youngcms.bean.OperateLog();
if(operateLog!=null){
operateLogBean.setModuleName(operateLog.moudleName());
operateLogBean.setOptName(operateLog.optName());
operateLogBean.setDescription(operateLog.description());
}
//请求的类名
String className = joinPoint.getTarget().getClass().getName();
//请求的方法名
String methodName = signature.getName();
//请求的参数
//Object[] args = joinPoint.getArgs();
operateLogBean.setIp(IPUtils.getIpAddr(HttpKit.getRequest()));
operateLogBean.setTime(time);
operateLogBean.setMethod(className+"."+methodName+"()");
operateLogBean.setUrl(classRequestMapping.value()[0]+mothodRequestMapping.value()[0]);
String username = ((SysUser) SecurityUtils.getSubject().getPrincipal()).getRealName();
operateLogBean.setAuthor(username);
operateLogBean.setCreateTime(DateUtil.dateToStr(new Date(), 12));
operateLogService.insert(operateLogBean);
} }
3、条件判断注解
ConditionalOnProperty 的意思是,当 usemysql.local 属性配置存在并且不为 false,则创建这个 bean
@Bean
@ConditionalOnProperty(
name = "usemysql",
havingValue = "local")
@ConditionalOnMissingBean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/myDb?createDatabaseIfNotExist=true");
dataSource.setUsername("mysqluser");
dataSource.setPassword("mysqlpass"); return dataSource;
}
4.获取 ip 地址工具类
ublic class IPUtils {
private static Logger logger = LoggerFactory.getLogger(IPUtils.class);
/**
* 获取IP地址
*
* 使用Nginx等反向代理软件, 则不能通过request.getRemoteAddr()获取IP地址
* 如果使用了多级反向代理的话,X-Forwarded-For的值并不止一个,而是一串IP地址,X-Forwarded-For中第一个非unknown的有效IP字符串,则为真实IP地址
*/
public static String getIpAddr(HttpServletRequest request) {
String ip = null;
try {
ip = request.getHeader("x-forwarded-for");
if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (StringUtils.isEmpty(ip) || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_CLIENT_IP");
}
if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
} catch (Exception e) {
logger.error("IPUtils ERROR ", e);
}
return ip;
}
}
5.读取配置文件
// 获取 config/constant.properties 文件中的配置内容
private static ResourceBundle bundle = ResourceBundle.getBundle("config/constant");
public static String fileUploadPath =bundle.getString("file-upload.dir");
6.字面量形式构建 list
public class DefaultSqlInjector extends AbstractSqlInjector {
@Override
public List<AbstractMethod> getMethodList(Class<?> mapperClass) {
return Stream.of(
new Insert(),
new Delete(),
new DeleteByMap(),
new DeleteById(),
new DeleteBatchByIds(),
new Update(),
new UpdateById(),
new SelectById(),
new SelectBatchByIds(),
new SelectByMap(),
new SelectOne(),
new SelectCount(),
new SelectMaps(),
new SelectMapsPage(),
new SelectObjs(),
new SelectList(),
new SelectPage()
).collect(toList());
}
}
7.版本序列化防止反序列化失败
实现序列化接口添加
private static final long serialVersionUID = 1L;
反序列化的时候,虚拟机同样会先读取该变量值,然后再当前读取的类中寻找同样的变量值,如果找到,那么反序列话成功,找不到即会报异常。
默认 serialVersionUID 由虚拟机计算,然而如果对象结构发生变化,该值也会变化,因此我们显示声明,虚拟机就不会再进行计算了,可以保证向后兼容性。
233
Java 中待总结工具类学习(自定义注解,读取配置,字面List)的更多相关文章
- Java中响应结果工具类,可自定义响应码,内容,响应消息
创建响应状态码和说明枚举类 /** * 响应状态码和说明 */public enum CodeEnum { SUCCESS(0, "成功!"), FAIL(1, &qu ...
- JAVA中封装JSONUtils工具类及使用
在JAVA中用json-lib-2.3-jdk15.jar包中提供了JSONObject和JSONArray基类,用于JSON的序列化和反序列化的操作.但是我们更习惯将其进一步封装,达到更好的重用. ...
- Java 中的并发工具类
Java 中的并发工具类 CountDownLatch public class JoinCountDownLatchTest { public static void main(String[] a ...
- java中常用的工具类(一)
我们java程序员在开发项目的是常常会用到一些工具类.今天我汇总了一下java中常用的工具方法.大家可以在项目中使用.可以收藏!加入IT江湖官方群:383126909 我们一起成长 一.String工 ...
- Java基础学习(五)-- Java中常用的工具类、枚举、Java中的单例模式之详解
Java中的常用类 1.Math : 位于java.lang包中 (1)Math.PI:返回一个最接近圆周率的 (2)Math.abs(-10):返回一个数的绝对值 (3)Math.cbrt(27): ...
- java中常用的工具类(三)
继续分享java中常用的一些工具类.前两篇的文章中有人评论使用Apache 的lang包和IO包,或者Google的Guava库.后续的我会加上的!谢谢支持IT江湖 一.连接数据库的综合类 ...
- java中常用的工具类(二)
下面继续分享java中常用的一些工具类,希望给大家带来帮助! 1.FtpUtil Java 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 ...
- Java中的并发工具类(CountDownLatch、CyclicBarrier、Semaphore、Exchanger)
在JDK的并发包里提供了很多有意思的并发工具类.CountDownLatch.CyclicBarrier和Semaphore 工具类提供了一种并发流程控制的手段,Exchanger 工具类则提供了在线 ...
- 在JAVA中封装JSONUtil工具类及使用
在JAVA中用json-lib-2.3-jdk15.jar包中提供了JSONObject和JSONArray基类,用于JSON的序列化和反序列化的操作.但是我们更习惯将其进一步封装,达到更好的重用. ...
随机推荐
- 阿里云 maven仓库地址配置
1. maven 配置文件配置settings.xml中设置mirror节点 <mirror> <id>nexus-aliyun</id> <mirrorOf ...
- 2019.12.4 Hystix熔断&Feign进行远程调用&Zuul
0.学习目标 会配置Hystix熔断 会使用Feign进行远程调用 能独立搭建Zuul网关 能编写Zuul的过滤器 1.Hystrix 1.1.简介 Hystrix,英文意思是豪猪,全身是刺,看起来就 ...
- 简单layer 快速上手
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title> ...
- 解决VS2017中使用scanf函数报错的问题
我们在VS2017中如果使用C语言的scanf输入函数,编译的时候编译器会报error C4996: 'scanf': This function or variable may be unsafe. ...
- go get 使用proxy来下载
http_proxy=https://127.0.0.1:1087 go get -v github.com/Shopify/sarama https_proxy=https://127.0.0.1: ...
- libhura的建立
libharu 是一个开源的导出pdf的库,在编译libharu需要用到zlib库和libpng库(libpng 依赖于zlib库).如果项目中不需要导出带有图片的pdf,可以将涉及到"pn ...
- Notepad++连接VMWare中Linux只能看到/root目录
如下图,使用SFTP协议连接,用root用户登录后,我一开始只能看到root下的文件.稍作修改,把下面的“Initial remote directory”设置成“/”就可以看到根目录了.
- shell 学习笔记5-shell-if语句
一.if条件语句 1.语法 1)单分支结构 第一种 if <条件表达式> then 指令 fi 第二种 if <条件表达式>:then 指令 fi 上文的"<条 ...
- asp.net后台或前端获取TemplateField绑定的文本
GridView中使用最多的一个是BoundField,还有一个是TemplateField 这两个各有其特点,BoundField的话比较简单,设置好DataField.HeaderText等就可以 ...
- WebApi 身份认 Basic基础认证
<body> <div style="text-align:center;"> <div>用户名:<input type="te ...