gpt4 book ai didi

java - 如何在运行时基于没有 XML 的 Spring 属性注入(inject)不同的服务

转载 作者:IT老高 更新时间:2023-10-28 13:51:34 24 4
gpt4 key购买 nike

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


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

@Autowired @Qualifier("selectorProperty") private MyService myService;

然后在 beans.xml 文件中我有一个别名,以便我可以使用 @Qualifier 中的属性。

<alias name="${selector.property}" alias="selectorProperty" />

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

@Component("Selector1")
public class MyServiceImpl1

@Component("Selector2")
public class MyServiceImpl2

application.properties

selector.property = Selector1

selector.property = Selector2

而关于工厂模式,在 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);
}

然后在您的 bean 中,您可以使用类似这样的东西在运行时根据属性的值获得正确的实现。

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

@Autowired private MyServiceFactory myServiceFactory;

private MyService myService;

@PostConstruct
public void postConstruct()
{
this.myService = myServiceFactory.getMyService(selectorProperty);
}

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


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

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

谢谢。

最佳答案

实际上,您可以通过在配置文件中将 ServiceLocatorFactory 声明为 bean 来使用不带 XML 的 ServiceLocatorFactory。

@Bean
public ServiceLocatorFactoryBean myFactoryServiceLocatorFactoryBean()
{
ServiceLocatorFactoryBean bean = new ServiceLocatorFactoryBean();
bean.setServiceLocatorInterface(MyServiceFactory.class);
return bean;
}

@Bean
public MyServiceFactory myServiceFactory()
{
return (MyServiceFactory) myFactoryServiceLocatorFactoryBean().getObject();
}

那么你仍然可以像往常一样使用工厂,但不涉及 XML。

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

@Autowired @Qualifier("myServiceFactory") private MyServiceFactory myServiceFactory;

private MyService myService;

@PostConstruct
public void postConstruct()
{
this.myService = myServiceFactory.getMyService(selectorProperty);
}

关于java - 如何在运行时基于没有 XML 的 Spring 属性注入(inject)不同的服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26463393/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com