您的位置:首页 > 编程语言

项目迭代之:创建时间覆盖优化、面向切面编程日志、权限管理、微服务

2020-08-04 20:27 656 查看

项目迭代之:创建时间覆盖优化、面向切面编程日志、权限管理、微服务

创建时间覆盖优化

一、在Util包下创建MyBeanUtils,实现对新闻进行更新时,不覆盖创建时间

package com.whut.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()]);
}
}

二、在NewsServiceImpl中加入getNullPropertyNames方法

@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包,包中创建LogAspect类实现日志的切面编程
二、在类前面加入注解@Aspect,@Component

@Aspect
@Component
public class LogAspect {}

三、定义log方法,找到切入点

private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Pointcut("execution(* com.guang.demo.web.*.*(..))")
public void log(){
}

四、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) +
'}';
}
}

五、定义在切点前后的日志打印方法

@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);
}

权限管理

一、修改ShiroConfiguration类中的shiroFilterFactoryBean方法

//配置shiro过滤工厂
@Bean
public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager){
ShiroFilterFactoryBean shiroFilterFactory = new ShiroFilterFactoryBean();
shiroFilterFactory.setSecurityManager(securityManager);
//通用配置
shiroFilterFactory.setLoginUrl("/admin");
shiroFilterFactory.setUnauthorizedUrl("/admin");//未授权
/*
* key: 请求路径
* value: 过滤器类型
*/
Map<String ,String > filterMap = new LinkedHashMap<>();
filterMap.put("/admin/news","perms[user-news]");
filterMap.put("/admin/types","perms[user-types]");
filterMap.put("/admin/tags","perms[user-tags]");
filterMap.put("/admin/login","anon");
filterMap.put("/admin/**","authc");

//设置过滤器
shiroFilterFactory.setFilterChainDefinitionMap(filterMap);
return shiroFilterFactory;
}

微服务

一、IDEA创建provider Module(Spring Cloud)步骤如下;
File→New→Module→Spring Initializr→Next→修改Group、Artifact、Java Version→Next→选择spring web、spring data JDBC、Mybatis framework、Mysql driver依赖→Next。
二、项目上级目录新建一个scloud文件夹,并修改root、location如下

三、修改pom.xml文件
添加依赖

<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper-spring-boot-starter</artifactId>
<version>2.0.4</version>
</dependency>

四、修改application.properties文件为application.yml文件
五、po下创建User

@Table(name = "tb_user")
public class User  implements Serializable {

private static final long serialVersionUID = -1203619350515120953L;

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String username;
private String password;
private String name;
private Integer age;
private Integer sex;
private Date birthday;
private Date created;
private Date updated;

public static long getSerialVersionUID() {
return serialVersionUID;
}

public Long getId() {
return id;
}

public void setId(Long id) {
this.id = id;
}

public String getUsername() {
return username;
}

public void setUsername(String username) {
this.username = username;
}

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public Integer getAge() {
return age;
}

public void setAge(Integer age) {
this.age = age;
}

public Integer getSex() {
return sex;
}

public void setSex(Integer sex) {
this.sex = sex;
}

public Date getBirthday() {
return birthday;
}

public void setBirthday(Date birthday) {
this.birthday = birthday;
}

public Date getCreated() {
return created;
}

public void setCreated(Date created) {
this.created = created;
}

public Date getUpdated() {
return updated;
}

public void setUpdated(Date updated) {
this.updated = updated;
}

@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", name='" + name + '\'' +
", age=" + age +
", sex=" + sex +
", birthday=" + birthday +
", created=" + created +
", updated=" + updated +
'}';
}
}

六、Usermapper

@org.apache.ibatis.annotations.Mapper
public interface UserMapper extends Mapper<User> {
}

七、UserService

@Service
public class UserService {

@Autowired(required = false)
private UserMapper userMapper;

public User queryById(Long id){
return this.userMapper.selectByPrimaryKey(id);
}

}

八、UserController

@RestController
@RequestMapping("user")
public class UserController {

@Autowired
private UserService userService;

@GetMapping("{id}")
public User queryById(@PathVariable("id") Long id){
return this.userService.queryById(id);
}
}

九、修改application.yml文件

server:
port: 8081
spring:
datasource:
url: jdbc:mysql://localhost:3306/sp_learn?useSSl=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai
username: root
password: ******
driver-class-name: com.mysql.cj.jdbc.Driver
mybatis:
type-aliases-package: com.roger.service.provider.po
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐