@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(一)的更多相关文章

  1. Halo 的缔造者们在忙什么?

    如果你自认为是一名主机游戏玩家,就一定知道 Halo.自 2001 年首代作品问世至今,十多年的磨炼已使得『光环』成为世界顶级的 FPS 游戏之一.<光环4>的推出,更让系列走向一个重要的 ...

  2. 超简单Centos+Docker+Halo搭建java向博客

    首先,我就当你们了解docker基本知识了. 直接开始,全新的系统. 1. 安装Docker 移除旧的版本:  $ sudo yum remove docker \                  ...

  3. 关于halo博客系统的使用踩坑——忘记登录密码

    踩坑: halo系统可以直接通过运行jar -jar halo-0.0.3.jar跑起来,也可以通过导入IDE然后运行Application的main方法跑起系统. h2数据库访问路径:http:// ...

  4. Halo(十三)

    Spring Boot Actuator 请求跟踪 Spring Boot Actuator 的关键特性是在应用程序里提供众多 Web 接口, 通过它们了解应用程序运行时的内部状况,且能监控和度量 S ...

  5. Halo(八)

    安全模块 用户描述类 /** * 基本 Entity */ @Data @MappedSuperclass public class BaseEntity { /** Create time */ @ ...

  6. Halo(七)

    @ControllerAdvice 对Controller进行"切面"环绕 结合方法型注解 @ExceptionHandler 用于捕获Controller中抛出的指定类型的异常, ...

  7. Halo(六)

    Spring publish-event 机制 监听者模式包含了一个监听者 Listener 与之对应的事件 Event,还有一个事件发布者 EventPublish. 过程就是 EventPubli ...

  8. Halo(五)

    ApplicationPreparedEvent 监听事件 Event published once the application context has been refreshed but be ...

  9. Halo博客的搭建

    今日主题:搭建一个私人博客 好多朋友和我说,能不能弄一个简单的私人博客啊,我说行吧,今天给你们一份福利啦! 搭建一个私人博客,就可以在自己的电脑上写博客了 Halo Halo 是一款现代化的个人独立博 ...

随机推荐

  1. boost IOStreams

    Boost.IOStreams provides numerous implementations of the two concepts. Devices which describes data ...

  2. python使用qq邮箱向163邮箱发送邮件、附件

    在生成html测试报告后 import smtplib,time from email.mime.text import MIMEText from email.mime.multipart impo ...

  3. ssm框架错误展示-1

    1.xmlParse错误+找不到bean ,一般会出现在导入别的地方拷来的项目时发生,报了以下错误: 查看自己的项目配置文件,发现spring的配置文件和sql映射xml文件都有个黄颜色的感叹号,鼠标 ...

  4. BZOJ 2806: [Ctsc2012]Cheat(单调队列优化dp+后缀自动机)

    传送门 解题思路 肯定先要建出来广义后缀自动机.刚开始以为是个二分+贪心,写了一下结果\(20\)分.说一下正解,首先显然\(L_0\)具有单调性,是可以二分的.考虑二分后怎样判合法,对于分割序列很容 ...

  5. Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2) 解决方法

    可以通过如下命令来解决,具体就是先关闭服务器,然后再重启服务器: cd /etc/init.d sudo service mysql stop sudo service mysql start

  6. PHP抓取远程图片到本地保存(如何把错误信息用text文件写入)

    最近在工作中需要开发了一个用户素材功能,里面需要将网上的各种图片素材进行本地化存储.于是在网上找了一些相关资料,并根据自身开发需要,整理了一下主要的逻辑代码. /** * PHP将网页上的图片攫取到本 ...

  7. qbxt Day2 on 19-7-25

    qbxt Day2 on 19-7-25 --TGZCBY 上午 1. 矩阵乘法在图论上的应用 有的时候图论的转移方程可以用dp的方式转移 特别是两个数的乘积求和的时候 比如邻接矩阵中f[i][j]表 ...

  8. 利用select单线程点对点聊天

    select的优点与使用方法 select用单线程的方法遍历所有待读写的I/O接口, 当有接口可用时就会返回. select可设置电脑阻塞或非阻塞. 特别注意: 每次select前都要重新初始化集合和 ...

  9. Selenium:八种元素定位方法

    前言: 我们在做WEB自动化时,最根本的就是操作页面上的元素,首先我们要能找到这些元素,然后才能操作这些元素.工具或代码无法像我们测试人员一样用肉眼来分辨页面上的元素.那么我们怎么来定位他们呢? 在学 ...

  10. C#后台将string="23.00"转换成int类型

    在C# 后台将String类型转换成int 有以下几种方法: (1)  int.TryParse(string); (2) Convert.Toint32(string); (3) (int)stri ...