【SSM】自定义属性配置的使用

首先,建立xxx.properties 文件在resource文件夹中,此处我们自定义的配置文件是oj-config.properties

然后,在applicationContext.xml中注册这个配置文件

    <!-- 自定义配置 -->
    <context:property-placeholder location="classpath*:oj-config.properties"/>

最后,在JAVA代码中使用注解配置到相应的属性上(特别注意,该属性不可以使用static修饰)

出现问题:

一开始将自定义属性配置在spring-mvc.xml文件中,并且在property-placeholder中使用了ignore-unresolvable="true"的属性。结果就是无法识别该配置路径,而是将localJudgePath配置成了“${oj.localJudgePath}",原因是因为在spring-mvc.xml中配置没有找到这个配置文件,且使用了ignore-unresolvable的属性,设置为true后在找不到配置的key后会直接设置为字符串。

解决问题:

将自定义属性配置定义在applicationContext中,删除spring-mvc.xml中的配置(这里其实是错误做法),解决了@Component组件中拿不到配置值的问题。

又遇到问题:

然后在@Controller中,发现无法读取到配置值,但是在@Component中是正常的。谷苟一下,发现需要在扫描@Controller组件后,重新配置一下属性文件,才能正确读取

解决问题:

在扫描@Controller后重新配置一下属性文件,把自定义属性配置的语句再放入spring-mvc.xml中,最终表现正常。

 

参考: https://blog.csdn.net/u010668907/article/details/79410665

    https://blog.csdn.net/u011017511/article/details/54427903

原文地址:https://www.cnblogs.com/axiangcoding/p/11355822.html