同じことを達成するためのさまざまな方法があります。以下は、春に一般的に使用されるいくつかの方法です-
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
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
Bean を登録します。
<bean id="properties"
class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="locations">
<list>
<value>classpath:path/filename.properties</value>
</list>
</property>
</bean>
Properties インスタンスをクラスに配線します-
@Component
public class BeanTester {
@Autowired Properties properties;
public void execute() {
String attr = properties.getProperty("ds.type");
}
}