我有以下bean声明:
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>WEB-INF/classes/config/properties/database.properties</value>
<value>classpath:config/properties/database.properties</value>
</list>
</property>
<property name="ignoreResourceNotFound" value="true"/>
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
Run Code Online (Sandbox Code Playgroud)
现在我想将上面的PropertyPlaceholderConfigurer更改为以下格式:
<context:component-scan base-package="org.example.config"/>
<util:properties id="jdbcProperties"
location="classpath:config/properties/database.properties"/>
Run Code Online (Sandbox Code Playgroud)
我正在使用Spring 3框架.
小智 47
<context:property-placeholder ... />是与PropertyPlaceholderConfigurer等效的XML.所以,更喜欢.在<util:properties/>简单的工厂一个java.util.Properties实例可以注入.
在Spring 3.1(而不是3.0 ......)中,您可以执行以下操作:
@Configuration
@PropertySource("/foo/bar/services.properties")
public class ServiceConfiguration {
@Autowired Environment environment;
@Bean public javax.sql.DataSource dataSource( ){
String user = this.environment.getProperty("ds.user");
...
}
}
Run Code Online (Sandbox Code Playgroud)
在Spring 3.0中,您可以使用SpEl注释"访问"使用PropertyPlaceHolderConfigurer机制定义的属性:
@Value("${ds.user}") private String user;
Run Code Online (Sandbox Code Playgroud)
如果要一起删除XML,只需使用Java配置手动注册PropertyPlaceholderConfigurer.我更喜欢3.1方法.但是,如果你使用Spring 3.0方法(因为3.1还不是GA ......),你现在可以像这样定义上面的XML:
@Configuration
public class MySpring3Configuration {
@Bean
public static PropertyPlaceholderConfigurer configurer() {
PropertyPlaceholderConfigurer ppc = ...
ppc.setLocations(...);
return ppc;
}
@Bean
public class DataSource dataSource(
@Value("${ds.user}") String user,
@Value("${ds.pw}") String pw,
...) {
DataSource ds = ...
ds.setUser(user);
ds.setPassword(pw);
...
return ds;
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,PPC是使用staticbean定义方法定义的.这是确保bean早期注册所必需的,因为PPC是BeanFactoryPostProcessor- 它可以影响bean本身在上下文中的注册,因此必须在其他所有内容之前注册.
Rya*_*art 19
首先,您不需要定义这两个位置.只是用classpath:config/properties/database.properties.在WAR中,WEB-INF/classes是一个类路径条目,因此它可以正常工作.
在那之后,我想你的意思是你想使用Spring的基于模式的配置来创建一个配置器.这将是这样的:
<context:property-placeholder location="classpath:config/properties/database.properties"/>
Run Code Online (Sandbox Code Playgroud)
请注意,您不再需要"ignoreResourceNotFound".如果需要使用util:properties以下方法单独定义属性:
<context:property-placeholder properties-ref="jdbcProperties" ignore-resource-not-found="true"/>
Run Code Online (Sandbox Code Playgroud)
但是,通常没有任何理由单独定义它们.
| 归档时间: |
|
| 查看次数: |
137640 次 |
| 最近记录: |