小编Ped*_*pez的帖子

如何在运行时基于Spring而不使用XML的属性注入不同的服务

我正在使用Spring Boot for Java独立应用程序.我有一个使用服务的bean.我想在运行时注入该服务的不同实现,基于Spring的属性文件中的属性(就此而言为4).


这听起来像工厂模式,但Spring也允许使用注释来解决问题,就像这样.

@Autowired @Qualifier("selectorProperty") private MyService myService;
Run Code Online (Sandbox Code Playgroud)

然后在beans.xml文件中我有一个别名,这样我就可以在@Qualifier中使用该属性.

<alias name="${selector.property}" alias="selectorProperty" />
Run Code Online (Sandbox Code Playgroud)

在我的不同实现中,我会有不同的限定符.

@Component("Selector1")
public class MyServiceImpl1

@Component("Selector2")
public class MyServiceImpl2
Run Code Online (Sandbox Code Playgroud)

application.properties

selector.property = Selector1

selector.property = Selector2
Run Code Online (Sandbox Code Playgroud)

而对于工厂模式,在Spring中,您可以使用ServiceLocatorFactoryBean来创建一个可以提供相同功能的工厂.

<bean
  class="org.springframework.beans.factory.config.ServiceLocatorFactoryBean"
  id="myServiceFactory">
  <property
    name="serviceLocatorInterface"
    value="my.company.MyServiceFactory">
  </property>
</bean>

public interface MyServiceFactory
{
    MyService getMyService(String selector);
}
Run Code Online (Sandbox Code Playgroud)

然后在您的bean中,您可以使用类似的东西在运行时获得正确的实现,具体取决于属性的值.

@Value("${selector.property}") private String selectorProperty;

@Autowired private MyServiceFactory myServiceFactory;

private MyService myService;

@PostConstruct
public void postConstruct()
{
    this.myService = myServiceFactory.getMyService(selectorProperty);
}
Run Code Online (Sandbox Code Playgroud)

但是这个解决方案的问题是我找不到一种方法来避免使用XML来定义工厂,我想只使用注释.


所以问题是,是否有一种方法可以仅使用注释来使用ServiceLocatorFactoryBean(或类似的东西),或者如果我不想在XML中定义bean,我是否被迫使用@Autowired @Qualifier方法?或者是否还有其他方法可以在运行时根据Spring 4避免使用XML的属性注入不同的服务?如果您的答案只是使用@Autowired @Qualifier别名,请说明为什么这比使用众所周知的工厂模式更好.

使用额外的XML迫使我@ImportResource("classpath:beans.xml")在我的Launcher类中使用,我也不愿意使用它.

谢谢.

java xml spring factory-pattern spring-boot

18
推荐指数
2
解决办法
3万
查看次数

使用Protractor的黄瓜HTML报告

我正在使用Protractor和Cucumber(js).我想生成报告文件,就像使用Cucumber-JVM版本一样.我看过使用Protractor和Jasmine的例子,但实际上没有使用Cucumber.

使用此配置时如何生成报告?

最终目标是在Jenkins或其他任何地方发布此报告(如果它们是直接在HTML中生成的).

谢谢!

reporting report cucumber protractor cucumberjs

13
推荐指数
2
解决办法
2万
查看次数