Существуют различные способы достижения того же. Ниже приведены некоторые часто используемые способы весной-
- Использование PropertyPlaceholderConfigurer
- Использование PropertySource
- Использование ResourceBundleMessageSource
Использование PropertiesFactoryBean
и многие другие ........................
Предполагая, что ds.type
является ключом в вашем файле свойств.
Использование PropertyPlaceholderConfigurer
Регистрация PropertyPlaceholderConfigurer
bean-
<context:property-placeholder location="classpath:path/filename.properties"/>
или
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations" value="classpath:path/filename.properties" ></property>
</bean>
или
@Configuration
public class SampleConfig {
@Bean
public static PropertySourcesPlaceholderConfigurer placeHolderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
//set locations as well.
}
}
После регистрации PropertySourcesPlaceholderConfigurer
вы можете получить доступ к значению-
@Value("${ds.type}")private String attr;
Использование PropertySource
В последней весенней версии вам не нужно регистрироваться PropertyPlaceHolderConfigurer
с @PropertySource
, я нашел хорошую ссылку , чтобы понять совместимость версий -
@PropertySource("classpath:path/filename.properties")
@Component
public class BeanTester {
@Autowired Environment environment;
public void execute() {
String attr = this.environment.getProperty("ds.type");
}
}
Использование ResourceBundleMessageSource
Register Bean-
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basenames">
<list>
<value>classpath:path/filename.properties</value>
</list>
</property>
</bean>
Значение доступа -
((ApplicationContext)context).getMessage("ds.type", null, null);
или
@Component
public class BeanTester {
@Autowired MessageSource messageSource;
public void execute() {
String attr = this.messageSource.getMessage("ds.type", null, null);
}
}
Использование PropertiesFactoryBean
Register Bean-
<bean id="properties"
class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="locations">
<list>
<value>classpath:path/filename.properties</value>
</list>
</property>
</bean>
Экземпляр свойств провода в ваш класс-
@Component
public class BeanTester {
@Autowired Properties properties;
public void execute() {
String attr = properties.getProperty("ds.type");
}
}