当我们想要读取使用xxx.yml文件中的一些属性值,只需要在定义的变量上加这个注解就可以。
情景举例:我把生成的用户token存入了redis中。然而,从web端存的token我用mobile作为key,从小程序mini端存的token我用UnionId作为key。 为了拿到用户对应的token,我就要先判断当前运行的是小程序还是web端,从而使用相应的key去找到我要的token。
在application.yml中,对于服务端的配置如下,我要根据contenx-path的内容进行判断:
首先定义一个变量,使用@Value(“${xxx}”)注解将属性赋值给变量:
具体使用如下
@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;
}
}
注意,如果是在static静态方法中使用,则赋值方式不同
因为这个@Value(“${xxx}”)注解是不能直接作用在static变量上的,因此,要用以下的方式赋值:
@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;
}
}



