Java:如何使用Spring注释将.properties文件的内容加载到Properties中?

时间:2018-10-10 04:28:08

标签: java spring

我在spring框架上使用Java 8。我有一个属性文件,其中包含“ =”分隔的值。我试图直接使用spring注释将属性文件的值加载到Property中。 例如 : 我的Application.properites具有:

screenWidth = UIScreen.main.bounds.width
        screenHeight = UIScreen.main.bounds.height
        radius = min(screenWidth,screenHeight)

        mainScroll.frame =  CGRect(x: 0, y: 90, width: screenWidth, height: screenHeight - 180)
        backView.frame = mainScroll.bounds
        imageView.frame = CGRect(x: 0, y: (screenHeight - radius)/2 - 80, width: radius, height: radius)
         backView.image = imageView.image
        let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.dark)
        let blurEffectView = UIVisualEffectView(effect: blurEffect)
        blurEffectView.frame = mainScroll.bounds
        blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        self.view.addSubview(mainScroll)
        self.mainScroll.addSubview(backView)
        self.backView.addSubview(blurEffectView)
        self.backView.addSubview(imageView)

并且我在context.xml中将该属性文件声明为:

cat=250
dog=560
lama=1000
donkey=650

现在在我的主类中,我试图将Application.properites中的所有值加载到

<util:properties id="app_props"
                 location="classpath*:/application.properties" />

,以便properties.getProperty(“ cat”)将返回“ 250”

不确定如何执行。我可以在这方面得到任何帮助吗?

1 个答案:

答案 0 :(得分:0)

按如下所示注册您的属性文件

  

XML Config

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:context="http://www.springframework.org/schema/context"
   xsi:schemaLocation="
      http://www.springframework.org/schema/beans 
      http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
      http://www.springframework.org/schema/context 
      http://www.springframework.org/schema/context/spring-context-4.2.xsd">

      <context:property-placeholder location="classpath:foo.properties" />

</beans> 
  

Java Config

@Configuration
@PropertySource("classpath:foo.properties")
public class PropertiesWithJavaConfig {
    //...
}
  

按如下方式使用属性

@Value( "${jdbc.url}" )
private String jdbcUrl;

您可以在我的GitHub存储库中找到完整的工作解决方案

https://github.com/mirmdasif/springmvc/tree/master/springproperties