在Spring 3中使用带有注释类的PropertyOverrideConfigurer

编辑 :这里有一些解释为什么被接受的答案对我有用,可能对其他人来说可能是个问题。

在我的foo-app-servlet.xml中,我有这一行:

 

当我之前使用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中的覆盖片段:

      

这是具有我想要覆盖的属性的类:

 @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 

我可以做我想做的事吗? 春季3有新的首选方式吗?

PropertyOverrideConfigurer使用属性文件中的键作为bean name.bean属性。 当@Component自动扫描您的配置时,Spring会将bean命名为以小写字母开头的非限定类名。 在您的情况下, OrderService bean应该命名为orderService 。 所以,以下应该有效。

 orderService.testMode=true 

您还可以通过将名称传递给Component注释(如@Component("OrderService")@Component("com.foo.services.OrderService")来命名bean。 这些都不是Spring 3.x中的新function。

希望这可以帮助

发布此非最佳解决方案:

您可以使用另一个bean解决此问题:

applicationContext.xml中:

      

OrderService.java:

 @Component public class OrderService { private static Log logger = LogFactory.getLog(OrderService.class); @Autowired @Qualifier("OrderDAO") private OrderDAO orderDao; @Autowired private SiteManager siteManager; @Autowired private SiteProperties siteProperties; String authorizenetProperties = "classpath:authorizenet.properties"; } 

因此,只需创建一个xml配置的bean并注入注释配置的bean。

如果有人知道,我仍然想知道“正确”的做法。

谢谢!