I'm trying to use a PropertyReader class to get my information (portNumber, hostName, etc) from a test.properties file in java spring, but I am pretty confused on how to go about this because there seems to be a million different ways (resource bundle etc)... I would greatly appreciate any input! Here's what my code looks like. Oh and the names are the same as in the properties file.
@Configuration
@PropertySource("classpath:test.properties")
public class PropertyReader {
private Environment environment;
String portNumber;
String hostName;
String subjectName;
String myUrl;
String portProtocol;
String hostProtocol;
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
public PropertyReader(String propertyFile) throws IOException {...}
I've already added
<context:property-placeholder location="classpath:test.properties" />
to my context. but not sure how to go about getting the info as environment.getProperty doesn't seem to be recognized as a function...
For what it's worth, this is how I do it: https://github.com/KevinWorkman/StaticVoidGames/blob/master/StaticVoidGames/src/main/java/com/StaticVoidGames/spring/config/PropertiesConfig.java
An example PropertiesConfig file:
@Configuration
@PropertySource("classpath:/live.properties")
public class PropertiesConfig {
@Value( "${property.name}" )
private String property;
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}
And here's how I use those properties from a Controller class: https://github.com/KevinWorkman/StaticVoidGames/blob/master/StaticVoidGames/src/main/java/com/StaticVoidGames/spring/controller/StaticVoidGamesController.java
@Component
public class ExampleController implements ExampleControllerInterface{
@Autowired
private Environment env;
public String viewHomePage(HttpServletRequest request, ModelMap model, HttpSession session){
String property = env.getProperty("property.name");
model.addAttribute("propertyValue", property);
return "index";
}
}
But you're right about there being a million different ways to do things. That's what makes programming so fun- and so frustrating!
I would recomend using Typesafe Configuration Properties, it keeps it litle bit cleaner and you do not need to use to many annotations.
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.