2017-02-10 75 views
2

是否有比在每个需要的类中调用loadProperties()更好的方法?在多个类中加载application.properties的正确方法是什么?

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。虽然这似乎不是正确方式

+0

为什么需要手动加载它?它也适用于任何Spring bean,只有'@ Service'注释的bean。 –

回答

1

春天在路上:第一种方法 还有一种方法是在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中使用属性将允许代码冗余。但您也可以提取此方法。

0

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

注意,它与任何Spring管理豆状 @Component,@Service,@Controller,@Repository

0

在不在服务,您可以使用原型作用域bean和使用的应用程序实例化它们的类案件你的函数中的上下文。

applicationContext.getBean("aScopedBean"); 

它们就像你通常的非singleton java对象,包含你在spring上下文中需要的bean。

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

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

如果您想避免@Autowire,那么您必须实现Utility函数或类。

相关问题