新闻管理系统新闻创建时间覆盖优化,以及面向切面编程日志运用
一.新闻创建时间覆盖优化
1.在Util包下创建MyBeanUtils工具类,实现对新闻进行更新时,不对创建时间进行覆盖
package com.guang.demo.util;
import org.springframework.beans.BeanWrapperImpl;
import java.beans.PropertyDescriptor;
import java.util.ArrayList;
import java.util.List;
public class MyBeanUtils {
public static String [] getNullPropertyNames(Object source){
BeanWrapperImpl beanWrapper = new BeanWrapperImpl(source);
PropertyDescriptor[] pds = beanWrapper.getPropertyDescriptors();
List<String> nullPropertyNames = new ArrayList<>();
for (PropertyDescriptor pd : pds) {
String propertyName = pd.getName();
if (beanWrapper.getPropertyValue(propertyName)==null){
nullPropertyNames.add(propertyName);
}
}
return nullPropertyNames.toArray(new String[nullPropertyNames.size()]);
}
}
2.在NewsServiceImpl中updateNew更新方法中,加入MyBeanUtils.getNullPropertyNames(news)方法
@Override
public News updateNew(Long id, News news) {
News news1 = newsRepository.findById(id).orElse(null);
if (news1==null){
System.out.println("未获得更新对象");
}
BeanUtils.copyProperties(news,news1, MyBeanUtils.getNullPropertyNames(news));
news1.setUpdateTime(new Date());
return newsRepository.save(news1);
}
二.面向切面编程日志运用
在项目中创建aspect包,在aspect中创建LogAspect类实现日志的切面编程运用
1.在类前面加入注解@Aspect,@Component
@Aspect
@Component
public class LogAspect {}
2.定义logger
private final Logger logger = LoggerFactory.getLogger(this.getClass());
3.定义log方法,找到切入点
@Pointcut("execution(* com.guang.demo.web.*.*(..))")
public void log(){
}
4.编写RequestLog内部类
private class RequestLog{
private String url;
private String ip;
private String classMethod;
private Object[] args;
public RequestLog(String url, String ip, String classMethod, Object[] args) {
this.url = url;
this.ip = ip;
this.classMethod = classMethod;
this.args = args;
}
@Override
public String toString() {
return "RequestLog{" +
"url='" + url + '\'' +
", ip='" + ip + '\'' +
", classMethod='" + classMethod + '\'' +
", args=" + Arrays.toString(args) +
'}';
}
}
5.定义在切点前后的日志打印方法
@Before("log()")
public void doBefore(JoinPoint joinPoint){
//获取Request
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
//获得url和ip....
String url = request.getRequestURL().toString();
String ip = request.getRemoteAddr();
String classMethod = joinPoint.getSignature().getDeclaringTypeName()+"."+joinPoint.getSignature().getName();
Object[] args = joinPoint.getArgs();
RequestLog requestLog = new RequestLog(url,ip,classMethod,args);
logger.info("Request : {}",requestLog);
logger.info("------------doBefore---------------");
}
@After("log()")
public void doAfter(){
logger.info("-------------doAfter--------------");
}
@AfterReturning(returning = "result",pointcut = "log()")
public void adAfterReturn(Object result){
logger.info("Result : {}",result);
}
6.后台输出打印结果