Spring can't find properties file

I tried all ways to find a file and always got this exception:

java.io.FileNotFoundException: class path resource [src/main/resources/sport.properties] cannot be opened because it does not exist

This is my folder structure:

folder structure

What path in this String is correct? @PropertySource("classpath:/src/main/resources/sport.properties")

Upvotes: 3

Views: 6687

Answers (2)

Stephen C
Stephen C

Reputation: 718678

What path in this String is correct? @PropertySource("classpath:/src/main/resources/sport.properties")

That is incorrect because you are mixing up two "name spaces".

  • The string "classpath:/src/main/resources/sport.properties" is a URI.

  • The "classpath" means you are telling Spring to look on the application's runtime classpath.

  • But "/src/main/resources/sport.properties" is not a name on the runtime classpath. Rather it is a pathname in the file system relative to the Eclipse project directory.

Since you are using Maven with Eclipse, you need to understand that the resources tree(s) get added to your classpath; i.e. "${MAVEN_PROJECT}/src/main/resources/a/b" becomes "/a/b" on the runtime classpath.

  • The "${MAVEN_PROJECT}/src/main/resources" directories for all Maven projects that make up your app are added to the classpath in this way.

  • When unit testing, "${MAVEN_PROJECT}/src/test/resources" directories get added ro the classpath as well.


In short, you should probably use @PropertySource("classpath:/sport.properties")

Upvotes: 6

notionquest
notionquest

Reputation: 39156

I would suggest using TestPropertySource as mentioned below for integration tests.

@RunWith(SpringRunner.class)
@ContextConfiguration(locations = "/applicationContext.xml")
@TestPropertySource(locations = "/sport.properties")

@TestPropertySource is a class-level annotation that is used to configure the locations() of properties files and inlined properties() to be added to the Environment's set of PropertySources for an ApplicationContext for integration tests.

Precedence:- Test property sources have higher precedence than those loaded from the operating system's environment or Java system properties as well as property sources added by the application declaratively via @PropertySource or programmatically (e.g., via an ApplicationContextInitializer or some other means). Thus, test property sources can be used to selectively override properties defined in system and application property sources. Furthermore, inlined properties() have higher precedence than properties loaded from resource locations().

Upvotes: 3

Related Questions