Доступ к нескольким файлам свойств с помощью @PropertyResource в Spring
Используя новую аннотацию @PropertySource
в Spring 3.1, как вы можете обращаться к нескольким файлам свойств с помощью среды?
В настоящее время у меня есть:
@Controller
@Configuration
@PropertySource(
name = "props",
value = { "classpath:File1.properties", "classpath:File2.properties" })
public class TestDetailsController {
@Autowired
private Environment env;
/**
* Simply selects the home view to render by returning its name.
*/
@RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Locale locale, Model model) {
String file1Name = env.getProperty("file1.name","file1.name not found");
String file2Name = env.getProperty("file2.name","file2.name not found");
System.out.println("file 1: " + file1Name);
System.out.println("file 2: " + file2Name);
return "home";
}
Результатом является правильное имя файла из File1.properties, но file2.name не найден. Как получить доступ к File2.properties?
Ответы
Ответ 1
существует два разных подхода:
первым из них является использование PropertyPlaceHolder в вашем applicationContext.xml:
beans-factory-placeholderconfigurer
<context:property-placeholder location="classpath*:META-INF/spring/properties/*.properties"/>
добавляемое пространство имен xmlns:context="http://www.springframework.org/schema/context"
Если вы хотите получить прямой доступ к переменной String в контроллере, используйте:
@Value("${some.key}")
private String valueOfThatKey;
Второй подход заключается в использовании util:properties
в вашем applicationContext.xml:
<util:properties id="fileA" location="classpath:META-INF/properties/a.properties"/>
<util:properties id="fileB" location="classpath:META-INF/properties/b.properties"/>
используя schemapLocations namesapce xmlns:util="http://www.springframework.org/schema/util"
: http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd
Затем в вашем контроллере:
@Resource(name="fileA")
private Properties propertyA;
@Resource(name="fileB")
private Properties propertyB;
Если вы хотите получить значение из файлов, просто используйте метод getProperty(String key)
Ответ 2
Если вы можете перейти на Spring 4.x, проблема была решена с помощью новой аннотации @PropertySources:
@PropertySources({
@PropertySource("/file1.properties"),
@PropertySource("/file2.properties")
})
Ответ 3
Несколько Properties
можно получить в Spring либо,
- @PropertySource ({ "name1", "name2" })
- @PropertySorces ({@PropertySource ( "name1" ), @PropertySource ( "name2" )})
Пример @PropertySource,
@PropertySource({
"classpath:hibernateCustom.properties",
"classpath:hikari.properties"
})
Пример @PropertySources,
@PropertySources({
@PropertySource("classpath:hibernateCustom.properties"),
@PropertySource("classpath:hikari.properties")
})
После указания пути Properties
вы можете получить к ним доступ через экземпляр Environment
, как вы обычно делали
ПРИМЕЧАНИЕ. Только для меня это просто не работало, хотя
Я получал компиляцию error
, поскольку я использовал значения свойств для настройки контекста приложения. Я пробовал все, что я нашел через Интернет, но они не работали для меня!
Пока я не сконфигурировал контекст Spring, как показано ниже,
applicationContext.setServletContext(servletContext);
applicationContext.refresh();
Пример
public class SpringWebAppInitializer implements WebApplicationInitializer{
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
// Create the 'root' Spring application context
AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext();
// register config class i.e. where i used @PropertySource
applicationContext.register(AppContextConfig.class);
// below 2 are added to make @PropertySources/ multi properties file to work
applicationContext.setServletContext(servletContext);
applicationContext.refresh();
// other config
}
}
Для вашей информации я использую Spring 4.3