我有一个ResourcesProperties.java类
@NoArgsConstructor
@PropertySource("classpath:config.properties")
@Component
public class ResourcesProperties {
@Bean
public static PropertySourcesPlaceholderConfigurer propertyConf() {
return new PropertySourcesPlaceholderConfigurer();
}
public static ResourcesProperties instance;
@Bean
public static ResourcesProperties getInstance() {
if (instance == null)
instance = new ResourcesProperties();
return instance;
}
@Getter
@Value("${room.rightStatusRoom}")
private static boolean rightStatusRoom;
@Getter
@Value("${room.countGuests}")
private static int countGuests;
}有一个"config.properties“属性文件
room.rightStatusRoom=true
room.countGuests=101为什么,当使用@Value注解访问of字段时,它们不从属性文件中返回指定的值?
示例:
if(ResourcesProperties.getInstance().isRightStatusRoom()) { //returned false instead true
//business-logic
}发布于 2020-02-06 16:45:36
我的解决方案是:
@NoArgsConstructor
@PropertySource("classpath:config.properties")
@Component
public class ResourcesProperties {
@Getter
@Value("${room.rightStatusRoom}")
private boolean rightStatusRoom;
@Getter
@Value("${room.countGuests}")
private int countGuests;
}发布于 2020-02-06 17:01:13
Spring不允许向静态对象注入值。因此您有两个选择,摆脱静态变量或调用设置静态变量的非静态设置器。更多信息可在此处找到:https://mkyong.com/spring/spring-inject-a-value-into-static-variables/
这些就是解决方案。
解决方案1:
@NoArgsConstructor
@PropertySource("classpath:config.properties")
@Component
public class ResourcesProperties {
@Getter
@Value("${room.rightStatusRoom}")
private boolean rightStatusRoom;
@Getter
@Value("${room.countGuests}")
private int countGuests;
}解决方案2:
@NoArgsConstructor
@PropertySource("classpath:config.properties")
@Component
public class ResourcesProperties {
@Getter
private static boolean rightStatusRoom;
@Getter
private static int countGuests;
@Value("${room.rightStatusRoom}")
public void setRightStatusRoom(boolean rightStatusRoom) {
this.rightStatusRoom = rightStatusRoom
}
@Value("${room.countGuests}")
public void setCountGuests(int countGuests) {
this.countGuests = countGuests
}
}https://stackoverflow.com/questions/60090633
复制相似问题