简体   繁体   English

在春季有条件地制作豆子

[英]Conditionally creating beans in spring

Right now I'm exposing the service layer of my application using spring remoting's RMI/SOAP/JMS/Hessian/Burlap/HttpInvoker exporters. 现在,我正在使用Spring Remoting的RMI / SOAP / JMS / Hessian / Burlap / HttpInvoker导出程序公开应用程序的服务层。 What I'd like is to allow the user to somehow define which of these remoting mechanisms they'd like enabled (rather than enabling all of them), then only create those exporter beans. 我想要的是允许用户以某种方式定义他们想要启用哪些远程处理机制(而不是启用所有远程处理机制),然后仅创建那些导出器bean。

I was hoping that spring's application context xml's had support for putting in conditional blocks around portions of the xml. 我希望spring的应用程序上下文xml支持在xml的各个部分周围放置条件块。 However, from what I've seen so far there's nothing in the standard spring distribution that allows you to do something like this. 但是,到目前为止,从我所看到的内容来看,标准的Spring发行版中没有任何东西可以让你做这样的事情。

Are there any other ways to achieve what I'm trying to do? 还有其他方法可以实现我的目标吗?

I am going to assume that you are looking to configure your application based on your environment, as in... for production I want to use this beans, in dev these other ... 我将假设您正在根据环境配置应用程序,例如在生产中,我想使用此bean,在其他开发中,使用...

As Ralph is saying, since Spring 3.1 you have profiles... But the key, is that you understand that you should put your environment based beans in different configuration files... so you could have something like dev-beans.xml, prod-beans.xml... Then in your main spring file, then you just invoke the appropriate one based on the environment that you are using... So profiles are only technique to do so... But you can also use other techniques, like have a system environmental variable, or pass a parameter in your build to decide which beans you want to use 就像Ralph所说的那样,从Spring 3.1开始,您就有了配置文件...但是关键是要了解,您应该将基于环境的Bean放在不同的配置文件中...这样您就可以拥有dev-beans.xml,prod之类的东西-beans.xml ...然后在您的主spring文件中,然后仅根据您使用的环境调用相应的文件...因此,概要文件只是这样做的技术...但是您也可以使用其他技术,例如具有系统环境变量,或在构建中传递参数来确定要使用的bean

You could realize this by using a Spring @Configuration bean, so you can construct your beans in java code. 您可以通过使用Spring @Configuration bean来实现这一点,因此可以用Java代码构造bean。 (see http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/beans.html#beans-java ) (请参阅http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/beans.html#beans-java

@Configuration
public class AppConfig {
  @Bean
  public MyService myService() {
      if ( userSettingIshessian ) {
          return new HessianExporter();
      }else {
          return new BurlapExporter();
      }
  }
}

Of course you need to get the user setting from somewhere, a system parameter would be easy, or config file, or something else. 当然,您需要从某处获取用户设置,使用系统参数或配置文件或其他方法。

Spring 3.1 has the concept of Profiles. Spring 3.1具有配置文件的概念。 My you can use them. 我可以使用它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM