英文:
Switching between profiles to manage multiple implementations on one spring interface
问题
以下是您要翻译的内容:
我正在尝试在不同的配置文件(profiles)中使用一个Spring接口的不同实现。我有多个在不同模块中的包含了代码的模块。接口和两个实现都在一个模块中,调用该接口的类则在另一个模块中。我的代码大致如下:
来自 module1:
public class FirstService {
@Autowired
private Interface interfaceImplementation;
}
来自 module2:
public interface Interface {
}
@Service
@Profile("develop")
public class InterfaceImpl1 implements Interface {
}
@Service
@Profile("test")
public class InterfaceImpl2 implements Interface {
}
当我启动应用程序时,应用程序无法启动,报错信息如下:
Field interface in FirstService required a bean of type Interface that could not be found
感谢您的帮助。
英文:
I am trying to use different implementations of a Spring Interface with different profiles. 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. My code is something like this:
from module1:
public class FirstService {
@Autowired
private Interface interfaceImplementation;
}
from module2:
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.
答案1
得分: 1
我通过将接口的基础包和独立模块中的实现添加到应用程序中的@ComponentScan中,成功解决了这个问题。
英文:
I was able to fix this issue by adding the base package of the interface, implementations that are in a separate module to the @ComponentScan in the application.
答案2
得分: 0
在您的应用程序启动时,它会在默认配置文件上启动,因此不会有类型为“Interface”的bean,因为在您的代码中,“Interface”的实现将仅在应用程序以“develop”或“test”配置文件启动时由Spring创建。在Spring中有许多设置配置文件的方法,最简单的方法是将其设置为系统参数或环境变量。
设置为系统参数的示例:
-Dspring.profiles.active=develop
或 -Dspring.profiles.active=test
(根据您正在运行的环境而定)
设置为环境变量的示例:
Linux:export spring_profiles_active=true
Windows:set spring_profiles_active=true
英文:
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. there are number of ways to set the profile in spring and easiest way set it as System parameter or environmental variable
Eg of setting as System parameter
-Dspring.profiles.active=develop
or -Dspring.profiles.active=test
(according which environment you are running)
Eg of setting as environmental variable
linux:- export spring_profiles_active=true
windows:- set spring_profiles_active=true
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论