来自另一个模块的 Spring Boot 自动装配

Ber*_*kin 12 java spring spring-boot

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

模块

在此处输入图片说明

所有这些模块都在 pom.xml 内部连接。说说我的问题吧。

C -> 路由.JAVA

.
.
.
@Autowired
public CommuniticationRepository;

@Autowired
public Core core;
.
.
.
Run Code Online (Sandbox Code Playgroud)

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

错误

com.demo.xyz.A.RestControllers.Route 中的 FieldcommunicationRepository 需要一个无法找到的“com.demo.xyz.A.CommunicationRepository”类型的 bean。

行动:

考虑在您的配置中定义一个“com.demo.xyz.A.CommunicationRepository”类型的 bean。

A - > REPOSITORY.JAVA

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

    List<Communication> findByDate(Date date);

    void countByDate(Date date);
}
Run Code Online (Sandbox Code Playgroud)

小智 13

如果它是 spring 数据 JPA 存储库,您应该删除@Component@Repositoryfrom CommunicationRepository

您应该在模块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 {

}
Run Code Online (Sandbox Code Playgroud)

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

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

}
Run Code Online (Sandbox Code Playgroud)


Dam*_*ith 7

基本上,如果您想在任何属性之上使用 @Autowired 注释并使用它,显然在 spring 上下文中应该有一个初始化的 bean 来将它自动装配到您的用法中。所以这里你的问题是在你的 spring 上下文中,没有这样的 bean 可以自动装配。所以解决方案是你需要在你的 spring 上下文中使用这些 bean,有多种方法可以完成这项工作,

您需要在 spring 上下文中将 bean 自动初始化为 @Component 的类

前任 :

@Component
public class Car{
Run Code Online (Sandbox Code Playgroud)

或者您可以手动拥有一个返回此类 bean 的配置文件

前任 :

@Bean
public Car setCarBean(){
    return new Car();
}
Run Code Online (Sandbox Code Playgroud)

这个 bean 返回应该在 @Configuration 类中。

请参考

那么如果你真的确定你已经完成了这个,那么正确的 @ComponentScan 应该可以工作

编辑

@SpringBootApplication 
@ComponentScan(basePackages = { "com.demo.xyz.A", "com.demo.xyz.B"}) 
public class Application {
Run Code Online (Sandbox Code Playgroud)