@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. el-tag标签使用三元表达动态改变type类型

    <el-tag :type="item.payCode=='在线' ? 'success' : 'danger'" >{{item.payCode}}</el-t ...

  2. 服务器构建CentOS+Jenkins+Git+Maven之爬坑

    ssh端口变更后,git如何访问远端中央代码库 参考来源: http://wiki.jenkins-ci.org/display/JENKINS/Git+Plugin http://blog.csdn ...

  3. 天池平台再升级,打造产业AI知识共享、技术共享平台

    在5月23日的云栖大会·武汉峰会上,天池发布“全球AI开发者计划”,打造一站式人工智能知识共享平台,计划2年内在平台上集聚30万AI工程师.同时,阿里云天池正式升级,成为从产业机会到实施交付一站式解决 ...

  4. django+nginx+uwsgi_cent0s7.4 部署

    django+nginx+uwsgi_cent0s7.4 部署 几条命令 # 查看是否有 uwsgi 相关的进程 ps -aux|grep "uwsgi" # 杀死有关 uwsgi ...

  5. Java Web学习总结(1)Tomcat使用教程

    一,简介 Tomcat是一个实现了JAVA EE标准的最小的WEB服务器,是Apache 软件基金会的Jakarta 项目中的一个核心项目,由Apache.Sun 和其他一些公司及个人共同开发而成.因 ...

  6. thinkphp 配置格式

    ThinkPHP支持多种格式的配置格式,但最终都是解析为PHP数组的方式. PHP数组定义 返回PHP数组的方式是默认的配置定义格式,例如: //项目配置文件 return [ // 默认模块名 'd ...

  7. Python操作 Memcache

    Memcached Memcached 是一个高性能的分布式内存对象缓存系统,用于动态Web应用以减轻数据库负载.它通过在内存中缓存数据和对象来减少读取数据库的次数,从而提高动态.数据 库驱动网站的速 ...

  8. mybatis Invalid bound statement (not found)错误解决办法

    由于新版的IntelliJ IDEA不再编译source folder下的xml文件,而我们平时使用mybatis时,习惯于将*Mapper.xml文件放在与dao层.service层平级的src目录 ...

  9. 存取cookies

    保存: Response.Cookies["OpenID"].Value = wxobj.openid; Response.Cookies["NickName" ...

  10. 电脑同时安装python2和python3 ,默认使用python3

    python3环境变量放在python2前面: 此电脑--属性--高级系统设置--高级--环境变量--系统变量--Path--编辑 D:\Python36\Scripts;D:\Python36;C: ...