在多个类中加载application.properties的正确方法是什么?

时间:2017-02-10 08:16:26

标签: java spring properties

有没有比在需要的每个类中调用loadProperties()更好的方法?

public void loadProperties() {
    InputStream inputStream;
    prop = new Properties();
    String propFileName = "application.properties";

    inputStream = getClass().getClassLoader().getResourceAsStream(propFileName);

    if (inputStream != null) {
        try {
            prop.load(inputStream);
        } catch (IOException e) {
            LOGGER.error("Error: ", e);
        }
    }
}

我知道Spring使用@Value注释提供了这个功能,但这仅在将类标记为@Service时才有效。虽然这似乎不是正确的方式

3 个答案:

答案 0 :(得分:1)

Spring in the way:第一种方法    在java代码中还有一种方法可以使用@Value批注来加载配置文件的值,在类@Component,@ Service,@ Controller,@ Repository上标记   例如:

   @Component("fileUpload") 
public class FileUploadUtil implements FileUpload { 

 private String filePath; 
 @Value("#{prop.filePath}") 
 public void setFilePath(String filePath) { 
  System.out.println(filePath); 
  this.filePath = filePath; 
 } 

bean.xml

<bean id="prop" class="org.springframework.beans.factory.config.PropertiesFactoryBean"> 
 <property name="locations">
  <array> 
   <value>classpath:public.properties</value> 
  </array> 
 </property> 
</bean> 

第二种方法:使用配置文件    例如:

   <context:property-placeholder location="classpath:conn.properties"/>
 <bean id="dataSource" class="${dataSource}"> 
 <property name="driverClass" value="${driverClass}" /> 
 <property name="jdbcUrl" value="${jdbcUrl}" /> 
 <property name="user" value="${user}" /> 
 <property name="password" value="${password}" /> 
 </bean> 

我认为这两种方法最简单。第二种方法不灵活。   使用属性的Java将允许代码冗余。但您也可以提取此方法。

答案 1 :(得分:0)

最好的方法是使用@Value注释。

请注意,它适用于任何Spring托管bean @ Component,@ Service,@ Controller,@ Repository

答案 2 :(得分:0)

如果类不是服务,您可以使用原型作用域bean并使用函数内的应用程序上下文对它们进行实例化。

applicationContext.getBean("aScopedBean");

它们就像你常用的非单例java对象,你需要从spring上下文中获取bean。

如果您想在地图中拥有属性,可以注入环境。

@Autowired
private Environment env;
...
env.getProperty("a_property");

如果你想避免@Autowire那么你必须实现一个效用函数或类。