编辑:这里解释了为什么接受的答案对我有用,以及对其他人来说可能是什么问题。
在我的 foo-app-servlet.xml 中,我有这一行:
<context:component-scan base-package="com.foo.app" />
我以前用spring2的时候,我所有的服务bean都来自于applicationContext.xml,现在直接在foo-app-servlet.xml中引入。在我的项目中,servlet 有自己的一组覆盖,因此我需要在 servlet 覆盖文件而不是 applicationContext 覆盖文件中进行覆盖。
覆盖时,如果您没有命名您的组件,那么它确实使用它的小写版本,因此要覆盖 OrderService.foo,您可以这样做:
orderService.foo=bar
结束编辑
我正在处理一个从 spring 2.5 升级到 spring 3 的项目,因此同时具有基于 xml 和注释的配置。我们之前已经使用 PropertyOverrideConfigurer 在不同的环境中更改属性并取得了巨大的成功。我现在正在处理使用 authorize.net 的代码,我需要确保我不会从开发环境向他们发送任何内容。
为了实现这一点,我想用 PropertyOverrideConfigurer 覆盖我的“testMode”属性。这对于通过 xml 配置的 bean 非常有用,但我无法弄清楚如何使用注释配置的类来完成它。
这是我从 applicationContext.xml 中覆盖的片段:
<bean class="org.springframework.beans.factory.config.PropertyOverrideConfigurer">
<property name="location" value="file:${user.home}/override.properties" />
<property name="localOverride" value="true" />
<property name="ignoreResourceNotFound" value="true" />
</bean>
这是具有我要覆盖的属性的类:
@Component
public class OrderService {
private static Log logger = LogFactory.getLog(OrderService.class);
@Autowired @Qualifier("OrderDAO") private OrderDAO orderDao;
@Autowired private SiteManager siteManager;
String authorizenetProperties = "classpath:authorizenet.properties";
private Boolean testMode = false;
public Boolean getTestMode() {
return testMode;
}
public void setTestMode(Boolean testMode) {
this.testMode = testMode;
}
}
我尝试了一些没有用的东西:
com.foo.services.OrderService.testMode=true
OrderService.testMode=true
是否可以在这里做我想做的事? spring 3 有新的首选方式吗?
最佳答案
PropertyOverrideConfigurer
使用属性文件中的键作为 bean name.bean 属性。当 @Component
自动扫描您的配置时,Spring 会将 bean 命名为以小写字母开头的非限定类名。在您的例子中,OrderService
bean 应该命名为 orderService
。因此,以下应该有效。
orderService.testMode=true
您还可以通过将名称传递给组件注释来命名 bean,例如 @Component("OrderService")
或 @Component("com.foo.services.OrderService")
。这些都不是 Spring 3.x 中的新内容。
希望对你有帮助
关于java - 在 Spring 3 中将 PropertyOverrideConfigurer 与带注释的类一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10034732/