简体   繁体   中英

Error trying to read properties file from WEB-INF directory in Spring

In my Java service, i'm trying to read the properties file as below

@Configuration
@ComponentScan(basePackages = { "com.site.xxx.*" })
@PropertySource("classpath:application.properties")
@Service("someService")
public class SomeService {
    @Autowired
    private Environment env;
    ...
}

And then in one of my methods, I do

String closeDate = env.getProperty("close.date");

There are 2 problems here either of which I could work with as a solution.

1> This works in a way that it does read the file if my application.properties file is in the classpath. I put it under src/main/resources and it reads the file BUT after I deploy the change, if I change the date inside this property file, it still shows me the first date which was entered when the code was compiled. So the reading part works but it doesn't change when I change the file contents.

2> If I change the contents of the following line

@PropertySource("classpath:WEB-INF/application.properties")

and if I place the file under my WEB-INF directory, even though the file is present, it says File Not Found.

I would very much prefer #2 to work but if there is no way that it can work (which I don't think), I can work with #1 as long as it behaves like a property file.

Spring loads the property files during the container startup , so whenever you change the property inside application.properties , you need to restart your server. So, that might be a reason your option(1) is not working.

If you wanted to work with option(2), you can configure the PropertySource with file: (not classpath: ) as shown below and you need to set myproject.home (or any other name of your choice) as the environment (OS) or system variable.

@PropertySource("file:${myproject.home}/WEB-INF/application.properties")

Do property file changes usually warrant a server restart?

Yes, they need a container restart.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM