gpt4 book ai didi

java - Spring Boot 从另一个模块 Autowiring

转载 作者:塔克拉玛干 更新时间:2023-11-01 23:01:00 26 4
gpt4 key购买 nike

我正在尝试在我的项目中的 3 个模块之间建立连接。当我尝试使用@Autowired 到达我的对象时,出现错误。我将稍微解释一下我的情况。

模块

enter image description here

所有这些模块都已在 pom.xml 中连接。让我们谈谈我的问题。

C -> ROUTE.JAVA

.
.
.
@Autowired
public CommuniticationRepository;

@Autowired
public Core core;
.
.
.

B -> 核心

public class Core {
private int id;
private String name;
private Date date;

public Core(int id, String name, Date date) {
this.id = id;
this.name = name;
this.date = date;
}

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public Date getDate() {
return date;
}

public void setDate(Date date) {
this.date = date;
}
}

错误

Field communicationRepositoryin com.demo.xyz.A.RestControllers.Route required a bean of type 'com.demo.xyz.A.CommunicationRepository' that could not be found.

Action:

Consider defining a bean of type 'com.demo.xyz.A.CommunicationRepository' in your configuration.

A->REPOSITORY.JAVA

@Component
@Repository
public interface CommunicationRepository extends CrudRepository<Communication, Date> {

List<Communication> findByDate(Date date);

void countByDate(Date date);
}

最佳答案

如果 CommunicationRepository 是 spring 数据 JPA 存储库,您应该从中删除 @Component@Repository

您应该在模块AB 中定义配置。

@Configuration
@EnableJpaRepositories(basePackages ={"com.demo.xyz.A"})
@EntityScan(basePackages = {"com.demo.xyz.A"})
@ComponentScan(basePackages = {"com.demo.xyz.A"})
public class ConfigA {

}

// If you have no spring managed beans in B this is not needed
// If Core should be a spring managed bean, add @Component on top of it
@Configuration
@ComponentScan(basePackages = {"com.demo.xyz.B"})
public class ConfigB {

}

然后,在 C 中引导应用程序的地方,您应该导入模块 A 和模块 B 的配置。此时,A 和 B 中的任何 bean 都可用于 C 中的 Autowiring .

@Configuration
@Import(value = {ConfigA.class, ConfigB.class})
public class ConfigC {

}

关于java - Spring Boot 从另一个模块 Autowiring ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52516360/

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