[英]Injecting library class as dependencies in spring project
我的项目中有多个库类,需要将它们注入服务类中。 这是IntegrationFactory类的错误语句:
考虑在配置中定义类型为“ com.ignitionone.service.programmanager.integration.IntegrationFactory”的bean。
几乎在每次注入该库类的地方都会出现此错误。
我已经在@ComponentScan中添加了Library包,但是由于它是只读文件,因此无法注释库类。 我从这里的一些答案中知道,Spring无法注入它无法管理的类。 该库不是在spring上构建的。
我试图创建一个@Bean方法,该方法在使用@Inject的类中返回IntegrationFactory(有问题的类),但这似乎也不起作用。
如何做到这一点,最好不要创建存根/复制类?
这是EngagementServiceImpl类的片段:
@Inject
public EngagementServiceImpl(EngagementRepository engagementRepository,
@Lazy IntegrationFactory integrationFactory, TokenRepository tokenRepository,
EngagementPartnerRepository engagementPartnerRepository, MetricsService metricsService) {
this.engagementRepository = engagementRepository;
this.integrationFactory = integrationFactory;
this.tokenRepository = tokenRepository;
this.engagementPartnerRepository = engagementPartnerRepository;
this.metricsService = metricsService;
}
这是注射部分:
@Autowired
private EngagementService engagementService;
这是ConfigClass:
@Configuration
public class ConfigClass {
@Bean
public IntegrationFactory getIntegrationFactory(){
Map<String, Object> globalConfig = new HashMap<>();
return new IntegrationFactory(globalConfig);
}
@Bean
@Primary
public EntityDataStore getEntityDataStore(){
EntityModel entityModel = Models.ENTITY;
return new EntityDataStore(this.dataSource(), entityModel );
}
@ConfigurationProperties(prefix = "datasource.postgres")
@Bean
@Primary
public DataSource dataSource() {
return DataSourceBuilder
.create()
.build();
}
}
您需要在配置类中添加bean定义。
@Configuration
public class ServiceConfig {
@Bean
public IntegrationFactory getIntegrationFactory(){
// return an IntegrationFactory instance
}
}
然后,您必须确保@Configuration
类被Spring检测到,方法是将其放在扫描路径中,或者通过@Import
从与扫描路径一起的某个位置手动将其导入。 @Import
的示例,考虑到您正在使用Spring Boot。
@Import(ServiceConfig.class)
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
希望这可以帮助!
找不到Bean IntegrationFactory
,因为它没有使用任何Spring构造型进行注释,因此无法被组件扫描识别。
由于您有多种选择可以向应用程序上下文提供类的实例,因此请阅读Spring文档(其中还包括示例)以找出最适合您的一种: https : //docs.spring.io/spring/docs /5.1.0.RELEASE/spring-framework-reference/core.html#beans-java-basic-concepts
一种选择是创建一个工厂,该工厂向应用程序上下文提供类的实例,如文档中所述:
@Configuration
public class AppConfig {
@Bean
public IntegrationFactory myIntegrationFactory() {
return new IntegrationFactory();
}
}
不要忘记将配置添加到应用程序上下文中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.