ImageService 中的字段 imageRepository 需要一个 ImageRepository' 类型的 bean,但无法找到

问题描述 投票:0回答:1

我正在开发一个多模块 spring 项目并收到以下错误:


应用程序无法启动


描述:

com.example.service.ImageService 中的字段 imageRepository 需要类型为“com.example.repository.IImageRepository”的 bean,但无法找到。

注入点有以下注释:

  • @org.springframework.beans.factory.annotation.Autowired(必需= true)

行动:

考虑在配置中定义“com.secureline.repository.IImageRepository”类型的 bean。

在使用模块之前我没有这个问题。 module-info.java 中的导出和要求检查出来,并且所有内容都在 IDE 本身内被识别。

运行 Spring 应用程序时出现上述错误

驻留在“view”模块中,具有启动 spring 项目的 main 方法 应用程序.java:

@SpringBootApplication
@EnableAutoConfiguration
@ComponentScan(basePackages = {
        "com.example.dto",
        "com.example.logger",
        "com.example.model",
        "com.example.repository",
        "com.example.security",
        "com.example.service"
})
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}

驻留在名为“service”的模块中

ImageService(省略服务逻辑,因为它对问题并不重要)

@Service("imageService")
public class ImageService implements IImageService {

    @Autowired
    private IImageRepository imageRepository;


    @Override
    public Image getById(Long id) {
        Optional<Image> result = imageRepository.findById(id);
        return result.orElseThrow(() -> new RuntimeException("Image not found for id: " + id));
    }

    @Override
    public List<Image> getAll() {
        return imageRepository.findAll();
    }

    @Override
    public void delete(Image image, Long performingUser) {
        imageRepository.delete(image);
    }

    @Override
    public Image save(Image image) {
        return imageRepository.save(image);
    }

    @Override
    public Image update(Image image, Long performingUser) throws AccessDeniedException {
        return imageRepository.save(image);
    }
}

驻留在 com.example.repository 包中名为“repository”的模块中; IImagine 存储库:

@Repository(value = "imageRepository")
public interface IImageRepository extends JpaRepository<Image, Long> {
}

我有点不知道这个问题在哪里,所以我非常感谢任何帮助!

java spring spring-boot spring-data-jpa spring-data
1个回答
0
投票

为什么你的 ImageRepository 在一个单独的模块中,它的目的是什么。 Spring 仅扫描包含主类的模块中的类。每个模块都被视为一个单独的应用程序。 要么将所有必需的类存储在一个模块中,要么使用第二个模块作为库并在主项目中添加对其的依赖项。 例如,使用 Maven 时,运行 mvn install 在本地存储库中找到您的库(模块),然后在 pom.xml 中添加对其的依赖项。

我重现了你的问题,最初给出了一个不完全正确的答案。除了上述之外,您还需要执行以下操作。在第二个模块中,创建一个配置类,例如:

@Configuration
@ComponentScan("com.example")
public Config{
}

然后在您的主模块中,在任何配置类或主类中添加此配置的导入。

@SpringBootApplication
@Import(Config.class)
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}
© www.soinside.com 2019 - 2024. All rights reserved.