如何在spring项目中读取属性文件? [英] how to read properties file in spring project?

查看:254
本文介绍了如何在spring项目中读取属性文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在发布此问题之前,我谷歌从Spring项目获取属性(它不是基于Web的项目)。我很困惑,因为每个人都在讨论application-context.xml,并且配置类似于

Before post this Question, I google to get Properties from Spring project(Its NOT web-based project). I am confused as every one are talking about application-context.xml and have configuration like

但是,我正在使用Spring进行正常的Java项目(NO网络应用程序和类似的东西)。但我想从属性文件中获取一些常见属性,并且需要在JAVA文件中使用。如何通过使用Spring / Spring Annotations实现这一目标?

However, I am working on normal Java Project with Spring(NO Web-app and stuff like that). But I would like to get some common properties from properties file and that needs to be used in JAVA file. How can achieve this by using Spring/Spring Annotations?

我应该在我的项目下配置myprops.properties文件以及如何通过spring调用?

Where I should configure myprops.properties file under my project and how to invoke through spring?

我的理解是application-context.xml仅用于基于Web的项目。如果没有,我应该如何配置这个application-context.xml,因为我没有web.xml来定义application-context.xml

My understanding is application-context.xml is used ONLY for web based projects. If not, how should I configure this application-context.xml as I do NOT have web.xml to define the application-context.xml

推荐答案

您可以创建基于XML的应用程序上下文,例如:

You can create an XML based application context like:

ApplicationContext ctx = new ClassPathXmlApplicationContext("conf/appContext.xml");

如果xml文件位于类路径上。或者,您可以在文件系统上使用文件:

if the xml file is located on your class path. Alternatively, you can use a file on the file system:

ApplicationContext ctx = new FileSystemXmlApplicationContext("conf/appContext.xml");

更多信息请参见 Spring参考文档。您还应注册关闭挂钩确保正常关机:

More information is available in the Spring reference docs. You should also register a shutdown hook to ensure graceful shutdown:

 ctx.registerShutdownHook();

接下来,您可以使用 PropertyPlaceHolderConfigurer 从'.properties'文件中提取属性并将它们注入到bean中:

Next, you can use the PropertyPlaceHolderConfigurer to extract the properties from a '.properties' file and inject them into your beans:

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations" value="classpath:com/foo/jdbc.properties"/>
</bean>

<bean id="dataSource" destroy-method="close" class="org.apache.commons.dbcp.BasicDataSource">
    <property name="driverClassName" value="${jdbc.driverClassName}"/>
    <property name="url" value="${jdbc.url}"/>
    <property name="username" value="${jdbc.username}"/>
    <property name="password" value="${jdbc.password}"/>
</bean>

最后,如果你更喜欢基于注释的配置,你可以使用 @Value 注释将属性注入到bean中:

Lastly, if you prefer annotation based config, you can use the @Value annotation to inject properties into you beans:

@Component
public class SomeBean {

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

这篇关于如何在spring项目中读取属性文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆