项目需求有一个值可以随时可以改变,此时就要求不能在后端代码中将其写死,比如登录用户密码的过期时间,我可以设置成一个月,也可以设置成一年,所以此时要求我们在配置文件中定义一个字段,在代码中读取这个字段,后续项目发布的时候只需要修改配置文件中的自定义字段就可以了。
方法一:@Value注解
在properties、yaml或者yml文件中设置自定义字段(此处我是在yaml文件中设置的)
# 设置密码有效时间时间以及失效提醒时间
password:
expired-time: 31
allowed-time: 25
如果在service的实现类中读取的话,就直接使用@Value注解读取
@Service
@Transactional
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
@Autowired
private UserMapper userMapper;
@Value("${password.expired-time}")
private long expiredTime;
@Value("${password.allowed-time}")
private long allowedTime;
System.out.println(expiredTime);
System.out.println(allowedTime);
}
如果实在controller层中,可以新建一个类,来存储自定义字段,再将这个类注入controller层中
新建类:
package com.example.healthylife_mall.utils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
* @ClassName Password 用来存储yaml文件中自定义的密码有效时间的字段
* @Author simon
* @Date 2022/10/31 0031 14:57
*/
@Component
public class PasswordUtil {
@Value("${password.expired-time}")
private long expiredTime;
@Value("${password.allowed-time}")
private long allowedTime;
public long getExpiredTime() {
return expiredTime;
}
public void setExpiredTime(long expiredTime) {
this.expiredTime = expiredTime;
}
public long getAllowedTime() {
return allowedTime;
}
public void setAllowedTime(long allowedTime) {
this.allowedTime = allowedTime;
}
}
controller层注入新建的类,在用类名打点调用该字段就可以获得了
/**
* 用户接口
* @ClassName liunian
* @Description TODO
* @Author @O_o
* @Date 2022/8/23 0023 16:31
* @Version 1.0
*/
@Slf4j
@CrossOrigin
@RestController
@RequestMapping("/user")
@AllArgsConstructor
public class UserController {
@Autowired
private UserService userService;
@Autowired
private PasswordUtil password;
/**
* 登录方法包含的代码逻辑:验证登录账号是否存在(正确)、验证登录用户密码时间是否在有效期、验证码判定、加载左菜单、按钮级别权限回显
* @param userDto
* @return
* @throws SystemException
*/
@PostMapping("/login")
public Object login(@RequestBody UserDto userDto) throws SystemException {
LoginData data = new LoginData();
data.setUser(userInfo);
data.setToken(Authorization);
data.setLayTable(layTable);
// 计算密码剩余有效时间
Date passwordTime = userInfo.getPasswordTime();
Date now = new Date();
Long time = (now.getTime()-passwordTime.getTime())/1000/60/60/24;
long gap = this.password.getExpiredTime()-time;
if (time> this.password.getExpiredTime()){