我正在使用spring应用程序,我正在尝试使用@Value注释从属性文件加载属性,但变量始终为null。
以下是我使用Annotated变量的代码:
@Service
public class RulesEngineServiceImpl implements IRulesEngineService {
@Value("${display.property}") static String displayProperty;
@Value("${return.enabled}") static boolean returnEnabled;
@Value("${return.type}") static String returnType;
@Value("${immediaterpi}") static boolean immediaterpi;
private static Rule getDefaultRule() {
LOG.info("applying default rule displayProperty ="+displayProperty+"| returnEnabled="+returnEnabled+"| returnType="+returnType+" | immediaterpi="+immediaterpi);
Rule rule = new Rule();
rule.setName("DEFAULT_RULE");
rule.setDisplayProperty(DisplayProperty.valueOf(displayProperty));
ActionProperty actionProperty = new ActionProperty();
ReturnActionVO returnAction = new ReturnActionVO(returnEnabled, returnType, immediaterpi);
actionProperty.setActions(JSONUtils.writeJson(returnAction));
rule.setActionProperty(actionProperty);
return rule;
}
}
这是名为application.prop的属性文件,其中定义了这些文件:
display.property=xzc
return.enabled=false
return.type=""
immediaterpi=false
我在这里提供了这个文件的参考:
@PropertySources({
@PropertySource("classpath:application.prop")})
public class PieApplication extends SpringBootServletInitializer
{
@Bean
public PieServletContextListener pieServletContextListener() {
return new PieServletContextListener();
}
public static void main(String[] args) throws Exception {
SpringApplication.run(PieApplication.class, args);
}
}
但是当我从其他代码中调用方法getDefaultRule()
时,它不会加载像displayProperty
这样的变量
并打印日志如下:
applying default rule displayProperty =null| returnEnabled=false| returnType=null | immediaterpi=false
请咨询。
修改 下面是代码更改,以防我使它们成为非静态
@Value("${display.property}") String displayProperty;
@Value("${return.enabled}") boolean returnEnabled;
@Value("${return.type}") String returnType;
@Value("${immediaterpi}") boolean immediaterpi;
private static Rule getDefaultRule() {
RulesEngineServiceImpl rulesEngineService = new RulesEngineServiceImpl();
LOG.info("applying default rule displayProperty ="+rulesEngineService.displayProperty+"| returnEnabled="+rulesEngineService.returnEnabled+"| returnType="+rulesEngineService.returnType+" | immediaterpi="+rulesEngineService.immediaterpi);
Rule rule = new Rule();
rule.setName("DEFAULT_RULE");
rule.setDisplayProperty(DisplayProperty.valueOf(rulesEngineService.displayProperty));
ActionProperty actionProperty = new ActionProperty();
ReturnActionVO returnAction = new ReturnActionVO(rulesEngineService.returnEnabled, rulesEngineService.returnType, rulesEngineService.immediaterpi);
actionProperty.setActions(JSONUtils.writeJson(returnAction));
rule.setActionProperty(actionProperty);
return rule;
}
但结果仍然相同。 我的问题是该字段何时初始化?如何从静态方法访问它,因为访问它的方法不能是非静态的?
答案 0 :(得分:1)
您不能在静态字段上使用@Value。使该字段非静态。
答案 1 :(得分:0)
默认情况下,Spring bean是单例,而使用@Value注释的字段只会设置一次。因此,不需要将它们定义为静态字段。此外,在单元测试期间,非静态字段更容易被模拟。