Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/350.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
spring mvc属性-java.io.FileNotFoundException:config.properties(系统找不到指定的文件)_Java_Spring_Hibernate - Fatal编程技术网

spring mvc属性-java.io.FileNotFoundException:config.properties(系统找不到指定的文件)

spring mvc属性-java.io.FileNotFoundException:config.properties(系统找不到指定的文件),java,spring,hibernate,Java,Spring,Hibernate,我已经创建了一个属性文件,并试图在我的spring DAO类文件中访问它,但是得到了“java.io.FileNotFoundException:config.properties(系统找不到指定的文件)”。我尝试了不同的方案将文件放在不同的文件夹/位置,但遇到了相同的问题。谁能帮我一下吗。以下是代码和结构细节 在道课上, FileReader reader = new FileReader("config.properties"); Properties properties = new Pr

我已经创建了一个属性文件,并试图在我的spring DAO类文件中访问它,但是得到了“java.io.FileNotFoundException:config.properties(系统找不到指定的文件)”。我尝试了不同的方案将文件放在不同的文件夹/位置,但遇到了相同的问题。谁能帮我一下吗。以下是代码和结构细节

在道课上,

FileReader reader = new FileReader("config.properties");
Properties properties = new Properties();
properties.load(reader);
我试图将“config.properties”文件放在src/main/resources
WEB-INF/
下。我的DAO类位于
src/main/java/com/test/DAO
提前感谢。

您可以在最合适的地方将文件保存在src/main/resources中,并将检索方式更改为:

ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("config.properties").getFile());
FileReader reader = new FileReader(file);

如果您试图读取属性文件,最佳做法是将其保存在src/main/resources文件夹中,根据spring,这是属性文件的默认位置。您可以使用注释来读取属性文件中的值,spring将自动读取并注入这些值

通过使用@value注释:

@Value( "${jdbc.url:aDefaultUrl}" )
private String jdbcUrl;
注意:这里您还可以指定默认值

通过使用xml配置:

<bean id="dataSource">
<property name="url" value="${jdbc.url}" />
<bean>
在这里,您可以提供要在类中映射的键,它将自动映射到字段

还可以指定多个特性文件,如:

@PropertySources({
@PropertySource("classpath:foo.properties"),
@PropertySource("classpath:bar.properties")
})

注意:请记住,要使其正常工作,属性文件应具有类似的扩展名。属性文件中的属性和值应遵循属性文件约定。

为什么不让Spring加载属性文件?假设它位于
src/main/resources
中,只需将
@PropertySource(“classpath:config.properties”)
添加到配置文件中(或者使用XML时添加
context:property placeholder location=“classpath:config.properties”
)。然后,您可以对dao中的属性使用
@Value
来访问它们,或者使用
环境
。太好了!Thx Deinum/Maciej正在工作,Maciej代码完成了工作@Deinum:如果我们没有使用spring属性进行检索,我希望没有问题?
@PropertySources({
@PropertySource("classpath:foo.properties"),
@PropertySource("classpath:bar.properties")
})