简体   繁体   English

在配置文件之间切换以管理一个 spring 接口上的多个实现

[英]Switching between profiles to manage multiple implementations on one spring interface

I am trying to use different implementations of a Spring Interface with different profiles.我正在尝试使用具有不同配置文件的 Spring 接口的不同实现。 I have multiple modules that have code in different modules.我有多个模块,它们在不同的模块中有代码。 Interface and 2 implementations are in a module and the class that calls the Interface is in a different module.接口和 2 个实现在一个模块中,调用接口的类在不同的模块中。 My code is something like this:我的代码是这样的:

from module1:来自模块 1:

public class FirstService {

    @Autowired
    private Interface interfaceImplementation;
}

from module2:从模块2:

public interface Interface {

}
@Service
@Profile("develop")
public class InterfaceImpl1 implements Interface {

}
@Service
@Profile("test")
public class InterfaceImpl2 implements Interface {

}

when I start my application, the application failed to start with the following error:当我启动我的应用程序时,应用程序无法启动并出现以下错误:

Field interface in FirstService required a bean of type Interface that could not be found

Thanks for the help.谢谢您的帮助。

While on you application is started up on your default profile so there will be no bean of type "Interface" because in your code Implementation of "Interace" will be created by spring only if your app is started in "develop" or "test" profile.当您的应用程序在您的默认配置文件上启动时,因此不会有“Interface”类型的 bean,因为在您的代码中,只有当您的应用程序在“develop”或“test”中启动时,spring才会创建“Interace”的实现轮廓。 there are number of ways to set the profile in spring and easiest way set it as System parameter or environmental variable有多种方法可以在 spring 中设置配置文件,最简单的方法是将其设置为系统参数或环境变量

Eg of setting as System parameter例如设置为系统参数

-Dspring.profiles.active=develop or -Dspring.profiles.active=test (according which environment you are running) -Dspring.profiles.active=develop-Dspring.profiles.active=test (根据您运行的环境)

Eg of setting as environmental variable例如设置为环境变量

linux:- export spring_profiles_active=true windows:- set spring_profiles_active=true linux:- export spring_profiles_active=true windows:- set spring_profiles_active=true

我能够通过将接口的基本包、单独模块中的实现添加到应用程序中的 @ComponentScan 来解决这个问题。

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

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