Как читать данные из файла свойств java с помощью Spring Boot
У меня есть приложение spring boot, и я хочу прочитать некоторую переменную из моего приложения.файл свойств. На самом деле ниже коды делают это. Но я думаю, что есть хороший метод для этой альтернативы.
Properties prop = new Properties();
InputStream input = null;
try {
input = new FileInputStream("config.properties");
prop.load(input);
gMapReportUrl = prop.getProperty("gMapReportUrl");
} catch (IOException ex) {
ex.printStackTrace();
} finally {
...
}
2 ответов
можно использовать @PropertySource
, чтобы выгрузить конфигурацию в файл свойств. Существует ряд способов сделать get properties:
1.
Назначьте значения свойств полям с помощью @Value
С PropertySourcesPlaceholderConfigurer
разрешить ${}
на @Value
:
@Configuration
@PropertySource("file:config.properties")
public class ApplicationConfiguration {
@Value("${gMapReportUrl}")
private String gMapReportUrl;
@Bean
public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() {
return new PropertySourcesPlaceholderConfigurer();
}
}
2.
Получить значения свойств с помощью Environment
:
@Configuration
@PropertySource("file:config.properties")
public class ApplicationConfiguration {
@Autowired
private Environment env;
public void foo() {
env.getProperty("gMapReportUrl");
}
}
надеюсь, это может помочь
Я бы предложил следующим образом:
@PropertySource(ignoreResourceNotFound = true, value = "classpath:otherprops.properties")
@Controller
public class ClassA {
@Value("${myName}")
String name;
@RequestMapping(value = "/xyz")
@ResponseBody
public void getName(){
System.out.println(name);
}
}
здесь ваше новое имя файла свойств - " otherprops.свойства "и имя свойства - "myName". Это самая простая реализация для доступа к файлу свойств в spring boot версии 1.5.8.