First of all, about the use of the @Value annotation, you can first learn about it through https://blog.csdn.net/yrsg666/article/details/111640131.
One of the usage methods is to read and use some attribute values in the xxx.yml file, so you only need to add this annotation to the defined variable.
Scenario example:
I stored the generated user token in redis. However, I use mobile as the key for the token stored on the web side, and I use UnionId as the key for the token stored on the mini program side. In order to get the token corresponding to the user, I must first determine whether the current running is a small program or a web terminal, so as to use the corresponding key to find the token I want.
In application.yml, the configuration of the server is as follows, I need to judge according to the content of contenx-path:
Non-static usage:
First define a variable, use the @Value("${xxx}") annotation to assign attributes to the variable: the
specific use is as follows
@Component
public class JwtUtils {
//定义一个普通变量然后赋值
@Value("${server.servlet.context-path}")
private String p;
public String getUserByToken(Integer userId) {
User user = userMapper.selectById(userId);
String plat = "/web";
//web端key是mobile
if (plat.equals(p)) {
token = redisService.getValue("user:token:" + user.getMobile());
}
//mini端key是UnionId
else {
token = redisService.getValue("user:token:" + user.getUnionId());
}
return token;
}
}
When used in a static static method, the assignment method is different
Because springboot cannot inject static variables, that is: @Value @Autowire @Resource cannot be used. Therefore, assign values in the following way:
@Component
public class JwtUtils {
//先定义一个普通变量,通过@Value注解赋值
@Value("${server.servlet.context-path}")
private String p;
//然后定义一个static变量
private static String platform;
//使用set的方式把普通变量的值赋给static静态变量
@Autowired
public void setPlatform() {
JwtUtils.platform = p;
}
public static String getUserByToken(Integer userId) {
User user = userMapper.selectById(userId);
String plat = "/web";
//web端key是mobile
if (plat.equals(platform)) {
token = redisService.getValue("user:token:" + user.getMobile());
}
//mini端key是UnionId
else {
token = redisService.getValue("user:token:" + user.getUnionId());
}
return token;
}
}