【问题标题】:Using a class to read a properties file, in Java, spring使用类读取属性文件,在Java中,spring
【发布时间】:2015-01-08 19:29:28
【问题描述】:

我正在尝试使用 PropertyReader 类从 java spring 中的 test.properties 文件中获取我的信息(端口号、主机名等),但我对如何去做这件事感到很困惑,因为似乎有一个百万种不同的方式(资源包等)......我将不胜感激任何输入!这是我的代码的样子。哦,名称与属性文件中的名称相同。

@Configuration
@PropertySource("classpath:test.properties")
public class PropertyReader  {


private Environment environment;

String portNumber;
String hostName;
String subjectName;
String myUrl;
String portProtocol;
String hostProtocol;

@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
    return new PropertySourcesPlaceholderConfigurer();
}
public PropertyReader(String propertyFile) throws IOException {...}

我已经添加了

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

我的上下文。但不确定如何获取环境信息。getProperty 似乎没有被识别为函数......

【问题讨论】:

    标签: java spring properties-file


    【解决方案1】:

    对于它的价值,我就是这样做的:https://github.com/KevinWorkman/StaticVoidGames/blob/master/StaticVoidGames/src/main/java/com/StaticVoidGames/spring/config/PropertiesConfig.java

    PropertiesConfig 文件示例:

    @Configuration
    @PropertySource("classpath:/live.properties")
    public class PropertiesConfig {
    
        @Value( "${property.name}" )
        private String property;
    
        @Bean
        public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
            return new PropertySourcesPlaceholderConfigurer();
        }
    }
    

    以下是我如何使用 Controller 类中的这些属性:https://github.com/KevinWorkman/StaticVoidGames/blob/master/StaticVoidGames/src/main/java/com/StaticVoidGames/spring/controller/StaticVoidGamesController.java

    @Component
    public class ExampleController implements ExampleControllerInterface{
    
        @Autowired
        private Environment env;
    
        public String viewHomePage(HttpServletRequest request, ModelMap model, HttpSession session){
    
            String property = env.getProperty("property.name");
            model.addAttribute("propertyValue", property);
    
            return "index";
        }
    }
    

    但你说得对,有一百万种不同的做事方式。这就是让编程变得如此有趣和令人沮丧的原因!

    【讨论】:

    • 快速提问这个代码'@Value("${property.name}")' - 我会为我拥有的每个变量做吗?对我来说,这会像 test.hostName 吗? (因为 test 是我的 .properties 文件名)?
    • @LoganStewart 是的!查看我用于更完整示例的实际源代码的链接。这只是为了以对 StackOverflow 友好的方式展示基础知识。
    • 一个问题,当我尝试自动装配环境时,它说它不能,因为没有找到bean,你知道为什么吗?再次感谢!
    【解决方案2】:

    我会推荐使用 Typesafe 配置属性,它会保持一点整洁,并且您不需要使用很多注释。

    http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html#boot-features-external-config-typesafe-configuration-properties

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-08
      • 2013-05-26
      • 2014-01-19
      • 2016-04-29
      • 1970-01-01
      • 2015-05-03
      • 2012-01-07
      • 1970-01-01
      相关资源
      最近更新 更多