Java 字段需要类型为。。。那是找不到的
在我的Java 字段需要类型为。。。那是找不到的,java,spring,spring-annotations,Java,Spring,Spring Annotations,在我的Spring项目中,我有一个界面: public interface MyIntefrace { void myMethod(String myParam); } 我有一个实现它的类: @Component @Profile("prod") public class MyImplementationClass implements MyInterface { ... 在我的另一个类中,我使用这个对象如下: @Autowired MyInterface myinterf
Spring
项目中,我有一个界面:
public interface MyIntefrace {
void myMethod(String myParam);
}
我有一个实现它的类:
@Component
@Profile("prod")
public class MyImplementationClass implements MyInterface {
...
在我的另一个类中,我使用这个对象如下:
@Autowired
MyInterface myinterface;
...
myinterface.myMethod(someParam);
这给我带来了一个错误:
Field myinterface in mypackage required a bean of type ... that could not be found.
The injection point has the following annotations:
- @org.springframework.beans.factory.annotation.Autowired(required=true)
Consider defining a bean of type '...' in your configuration
我试图在
MyInterface
上面添加@Service
注释,但没有任何帮助。我还可以做什么?确保启用了prod
配置文件,例如:
-Dspring.profiles.active=prod
export-spring\u profiles\u active=prod
ApplicationContext
时以编程方式:
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
//...........
ctx.getEnvironment().setActiveProfiles("prod");
ctx.refresh();
确保
prod
配置文件处于启用状态,例如通过以下方式:
-Dspring.profiles.active=prod
export-spring\u profiles\u active=prod
ApplicationContext
时以编程方式:
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
//...........
ctx.getEnvironment().setActiveProfiles("prod");
ctx.refresh();
@KenChan提供的答案已经提到了一个可行的解决方案,但我想补充一些额外的细节。目前,您只有一个
MyIntefrace
的实现,该实现还带有@Profile
注释。如果您不使用此配置文件运行应用程序,则无法创建依赖于该bean的所有其他bean(并且不可选地使用getter/setter注入进行注入)
我建议您创建第二个实现,如果您的概要文件未激活,则将注入该实现,或者使用该概要文件注释所有依赖的bean
@Component
@Profile("prod")
public class MyImplementationClass implements MyInterface {
// ...
}
@Component
@Profile("!prod") // second implementation, used if 'prod' is not active
public class MyImplementationClass implements MyInterface {
// ...
}
@KenChan提供的答案已经提到了一个可行的解决方案,但我想补充一些额外的细节。目前,您只有一个
MyIntefrace
的实现,该实现还带有@Profile
注释。如果您不使用此配置文件运行应用程序,则无法创建依赖于该bean的所有其他bean(并且不可选地使用getter/setter注入进行注入)
我建议您创建第二个实现,如果您的概要文件未激活,则将注入该实现,或者使用该概要文件注释所有依赖的bean
@Component
@Profile("prod")
public class MyImplementationClass implements MyInterface {
// ...
}
@Component
@Profile("!prod") // second implementation, used if 'prod' is not active
public class MyImplementationClass implements MyInterface {
// ...
}
如何扫描spring组件?如何启动应用程序?您定义了在概要文件“prod”中可用的组件。您启用了该配置文件吗?e、 g.
--spring.profiles.active=prod
作为命令行参数如何扫描spring组件?如何启动应用程序?您定义了在概要文件“prod”中可用的组件。您启用了该配置文件吗?e、 g.--spring.profiles.active=prod
作为命令行参数,您还可以使用spring.profiles.active=prod
将其添加到application.properties
文件中。我没有看到@randomuser1 addspring boot
标记,因此我假设它是一个非spring boot应用程序,我怀疑application.properties
是否可以在spring开箱即用中工作……您还可以使用spring.profiles.active=prod
将其添加到应用程序.properties
文件中,application.properties
来自spring boot。我没有看到@randomuser1添加spring boot
标记,所以我假设它是一个非spring boot应用程序,我怀疑应用程序。属性
将在spring开箱即用中工作。。。