Halo(一)
@EnableJpaAuditing 审计功能(启动类配置)
在实际的业务系统中,往往需要记录表数据的创建时间、创建人、修改时间、修改人。
每次手动记录这些信息比较繁琐,SpringDataJpa 的审计功能可以帮助我们来做这些繁琐的配置。
1. 在 spring jpa 中,支持在字段或者方法上进行注解:
@CreatedDate、@CreatedBy、
@LastModifiedDate、@LastModifiedBy
@CreatedDate:
表示该字段为创建时间时间字段,在这个实体被insert的时候,会设置值
@CreatedBy:
表示该字段为创建人,在这个实体被insert的时候,会设置值
2. 在类上加上注解 @EntityListeners(AuditingEntityListener.class)
3. 在 application启动类 中加上注解 @EnableJpaAuditing
4. 这个时候,在jpa的save方法被调用的时候,时间字段会自动设置并插入数据库,
但是CreatedBy和LastModifiedBy并没有赋值,因为需要实现AuditorAware接口来返回你需要插入的值。
@Configuration //使用jpa审计功能,保存数据时自动插入创建人id和更新人id
public class UserAuditorAware implements AuditorAware<Long> {
@Override
public Optional<Long> getCurrentAuditor() {
//从session中获取当前登录用户的id
Long userId = 2L;
return Optional.of(userId);
}
}
@EnableScheduling 定时任务(启动类配置)
1. 在 application 启动类中加上注解 @EnableScheduling 开启对定时任务的支持。
2. 在相应的方法上添加 @Scheduled 声明需要执行的定时任务。
@Component
public class SchedulingConfig {
//设置每5秒执行一次。或者:@Scheduled(fixedRate = 5000,initialDelay = 0)
@Scheduled(cron = "0/5 * * * * ?")
public void getToken() {
System.Out.printf("now time:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
}
@EnableAsync 多线程支持(启动类配置)
SpringBoot 提供了注解 @EnableAsync + @Async 实现方法的异步调用。
1. 在启动类上加上 @EnableAsync 注解开启项目的异步调用功能。
2. 在需异步调用的方法上加上注解 @Async 即可实现方法的异步调用。
异步的方法有3种
1. 最简单的异步调用,返回值为void
2. 带参数的异步调用,异步方法可以传入参数
3. 异步调用返回Future
@Component
public class AsyncTask {
@Async
public Future<String> task() throws InterruptedException{
Thread.sleep(1000);
return new AsyncResult<String>("task执行完毕");
}
}
@RestController
public class AsyncTaskController {
@Autowired
private AsyncTask asyncTask;
@RequestMapping("/")
public String doTask() throws InterruptedException{
Future<String> task = asyncTask.task();
return task.get();
}
}
@EnableJpaRepositories 用来扫描和发现指定包及其子包中的Repository定义(启动类配置)
简单配置,格式如下:
@EnableJpaRepositories("repository")
配置支持多个package,格式如下:
@EnableJpaRepositories({"repository1", "repository2"})
配置扫描Repositories所在的package及子package:
@EnableJpaRepositories(basePackages = "repository")
指定Repository类
@EnableJpaRepositories(basePackageClasses = BookRepository.class)
加载配置文件
Spring Boot 默认加载配置文件的位置是:
//后面会覆盖前面的
classpath:/,
classpath:/config/,
file:./,
file:./config/
Spring 定义的外部文件名称参数(优先级最高):
public static final String CONFIG_ADDITIONAL_LOCATION_PROPERTY = "spring.config.additional-location";
//设置为全局变量
System.setProperty("spring.config.additional-location", "file:${user.home}/.halo/,file:${user.home}/halo-dev/");
@ConfigurationProperties 把配置文件信息读取并自动封装成实体类
配置文件(Properties文件):
connection.username=admin
connection.password=aaa
connection.remoteAddress=192.168.1.1
@Data
@Component
@ConfigurationProperties(prefix="connection")
public class ConnectionSettings {
private String username;
private String remoteAddress;
private String password ;
}
或者
@Configuration
public class Conf{
@Bean
@ConfigurationProperties(prefix = "connection")
public ConnectionSettings connectionSettings(){
return new ConnectionSettings();
}
}
使用
@Component
@EnableConfigurationProperties(Conf.class)
public class Test {
@Autowired
private Conf conf;
}
ObjectMapper 配置 SpringMVC 默认的解析工具 Jackson(json和java之间的相互转化)(配置类 @Configuration 中)
ObjectMapper:
package com.fasterxml.jackson.databind;
@Bean
public ObjectMapper objectMapper(Jackson2ObjectMapperBuilder builder) {
//如果是空对象的时候,不抛异常
builder.failOnEmptyBeans(false);
return builder.build();
}
//序列化的时候序列对象的所有属性
objectMapper.setSerializationInclusion(Include.ALWAYS);
//反序列化的时候如果多了其他属性,不抛出异常
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
//如果是空对象的时候,不抛异常
objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
//属性值为null的不参与序列化
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
//取消时间的转化格式,默认是时间戳,可以取消,同时需要设置要表现的时间格式
objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"))
RestTemplate REST服务API(配置类 @Configuration 中)
RESTful风格的Web服务架构,其目标是为了创建具有良好扩展性的分布式系统。
REST主要是用于定义接口名,接口名一般是用名词写,不用动词。
RestTemplate:
package org.springframework.web.client;
Spring 框架提供的 RestTemplate 类可用于在应用中调用 rest 服务。
它简化了与 http 服务的通信方式,统一了 RESTful 的标准,封装了 http 链接, 我们只需要传入 url 及返回值类型即可。
RestTemplate 默认依赖 JDK 提供 http 连接的能力(HttpURLConnection)。
如果有需要的话也可以通过 setRequestFactory() 方法替换。
@Bean
public RestTemplate httpsRestTemplate(RestTemplateBuilder builder) {
RestTemplate httpsRestTemplate = builder.build();
httpsRestTemplate.setRequestFactory(
new HttpComponentsClientHttpRequestFactory(HttpClientUtils.createHttpsClient(TIMEOUT)));
return httpsRestTemplate;
}
RestTemplate 包含以下几个部分:
HttpMessageConverter 对象转换器
ClientHttpRequestFactory 默认是JDK的HttpURLConnection
ResponseErrorHandler 异常处理
ClientHttpRequestInterceptor 请求拦截器
HttpClient
HttpClient:
package org.apache.http.client;
HttpClient相比传统JDK自带的URLConnection,增加了易用性和灵活性:
它不仅使客户端发送Http请求变得容易,而且也方便开发人员测试接口(基于Http协议的),
提高了开发的效率,也方便提高代码的健壮性。
/**
* Http client 工具类
*/
public class HttpClientUtils {
/** 默认超时时间:5s */
private final static int TIMEOUT = 5000;
private HttpClientUtils() {
}
/**
* 创建 https client
*/
@NonNull
public static CloseableHttpClient createHttpsClient(int timeout) throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
//配置安全套接字SSL(获取不需要ssl认证的httpClient实例)
SSLContext sslContext = new SSLContextBuilder()
//解决https时的证书报错问题,信任所有证书
.loadTrustMaterial(null, (certificate, authType) -> true)
.build();
return HttpClients.custom()
.setSSLContext(sslContext)
//配置主机名验证(接受任何有效的SSL会话来匹配目标主机)
.setSSLHostnameVerifier(new NoopHostnameVerifier())
//默认请求配置
.setDefaultRequestConfig(getReqeustConfig(timeout))
.build();
}
/**
* HttpClient内部三个超时时间的配置
*/
private static RequestConfig getReqeustConfig(int timeout) {
//用RequestConfig类的静态方法custom()获取RequestConfig.Builder配置器
return RequestConfig.custom()
.setConnectionRequestTimeout(timeout) //从连接池中获取连接的超时时间
.setConnectTimeout(timeout) //与服务器连接超时时间
.setSocketTimeout(timeout) //从服务器获取响应数据的超时时间
.build(); //调用配置器的build()方法返回RequestConfig对象。
}
}
RequestConfig HttpClient配置
RequestConfig:
package org.apache.http.client.config;
/**
* HttpClient内部三个超时时间的配置
*/
private static RequestConfig getReqeustConfig(int timeout) {
//用RequestConfig类的静态方法custom()获取 RequestConfig.Builder配置器
return RequestConfig.custom()
.setConnectionRequestTimeout(timeout) //从连接池中获取连接的超时时间
.setConnectTimeout(timeout) //与服务器连接超时时间
.setSocketTimeout(timeout) //从服务器获取响应数据的超时时间
.build(); //调用配置器的build()方法返回RequestConfig对象。
}
Halo(一)的更多相关文章
- Halo 的缔造者们在忙什么?
如果你自认为是一名主机游戏玩家,就一定知道 Halo.自 2001 年首代作品问世至今,十多年的磨炼已使得『光环』成为世界顶级的 FPS 游戏之一.<光环4>的推出,更让系列走向一个重要的 ...
- 超简单Centos+Docker+Halo搭建java向博客
首先,我就当你们了解docker基本知识了. 直接开始,全新的系统. 1. 安装Docker 移除旧的版本: $ sudo yum remove docker \ ...
- 关于halo博客系统的使用踩坑——忘记登录密码
踩坑: halo系统可以直接通过运行jar -jar halo-0.0.3.jar跑起来,也可以通过导入IDE然后运行Application的main方法跑起系统. h2数据库访问路径:http:// ...
- Halo(十三)
Spring Boot Actuator 请求跟踪 Spring Boot Actuator 的关键特性是在应用程序里提供众多 Web 接口, 通过它们了解应用程序运行时的内部状况,且能监控和度量 S ...
- Halo(八)
安全模块 用户描述类 /** * 基本 Entity */ @Data @MappedSuperclass public class BaseEntity { /** Create time */ @ ...
- Halo(七)
@ControllerAdvice 对Controller进行"切面"环绕 结合方法型注解 @ExceptionHandler 用于捕获Controller中抛出的指定类型的异常, ...
- Halo(六)
Spring publish-event 机制 监听者模式包含了一个监听者 Listener 与之对应的事件 Event,还有一个事件发布者 EventPublish. 过程就是 EventPubli ...
- Halo(五)
ApplicationPreparedEvent 监听事件 Event published once the application context has been refreshed but be ...
- Halo博客的搭建
今日主题:搭建一个私人博客 好多朋友和我说,能不能弄一个简单的私人博客啊,我说行吧,今天给你们一份福利啦! 搭建一个私人博客,就可以在自己的电脑上写博客了 Halo Halo 是一款现代化的个人独立博 ...
随机推荐
- 第一周作业—N42-虚怀若谷
一.Linux发行版描述. Linux发行版主要有三个分支:Slackware.Debian.Redhat: (1) Slackware: SUSE:基于Slackware二次开发的一款Linux,主 ...
- vim编辑器的使用技巧——忽略字母大小写
一忽略字母大小写临时生效 底行模式 底行模式下输入set ic 注意ic是ignorecase的缩写 命令模式 命令模式进行关键字搜索 二忽略字母大小写永久生效 保存到配置文件里面,默认是没有此配置 ...
- Android逆向之旅---Android应用的汉化功能(修改SO中的字符串内容)
一.前言 今天我们继续来讲述逆向的知识,今天我们来讲什么呢?我们在前一篇文章中介绍了关于SO文件的格式,今天我们继续这个话题来看看如何修改SO文件中的内容,看一下我们研究的主题: 需求:想汉化一个Ap ...
- vue项目git
https://github.com/renrenio/renren-fast-vue https://github.com/hzlshen/vue-project
- JQUERY的$(function(){})和window.onload=function(){}的区别【转】
在Jquery里面,我们知道入口函数有两种写法:$(function(){}) 和$(document).ready(function(){}) 作用类似于传统JavaScript中的window.o ...
- selenium2-java 浏览器cookie的获取
//成功登陆后增加如下代码 File cookieFile = new File("C:\\tmp\\tangdai.cookie.txt"); ...
- [题解]Yet Another Subarray Problem-DP 、思维(codeforces 1197D)
题目链接:https://codeforces.com/problemset/problem/1197/D 题意: 给你一个序列,求一个子序列 a[l]~a[r] 使得该子序列的 sum(l,r)-k ...
- 有根树的表达 Aizu - ALDS1_7_A: Rooted Trees
有根树的表达 题目:Rooted Trees Aizu - ALDS1_7_A A graph G = (V, E) is a data structure where V is a finite ...
- Java集合的介绍
参考博客: https://blog.csdn.net/zhangqunshuai/article/details/80660974 List , Set, Map都是接口,前两个继承至Collect ...
- 转:inline-block 前世今生
曾几何时,display:inline-block 已经深入「大街小巷」,随处可见 「display:inline-block; *display:inline; *zoom:1; 」这样的代码.如今 ...