小编典典

Spring Boot:从库项目自动装配bean

spring-boot

我正在努力从我的自定义库(通过gradle导入)自动装配bean。阅读了几个类似的主题后,我仍然找不到解决方案。

我有依赖于其他项目的Spring
Boot项目(我的自定义库以及Components,Repositories等…)。这个库是一个Spring不可运行的jar,主要由域实体和存储库组成。它没有可运行的Application.class和任何属性…

当我启动应用程序时,我可以看到我的’CustomUserService’bean(来自库)正在尝试初始化,但是自动装配到其中的bean无法加载(接口UserRepository)…

错误:

com.myProject.customLibrary.configuration.CustomUserDetailsS​​ervice中构造函数的参数0需要找不到类型为com.myProject.customLibrary.configuration.UserRepository的bean。

我什至尝试设置’Order’,以显式加载它(使用’scanBasePackageClasses’),使用包和标记类进行扫描,添加其他’EnableJPARepository’注释,但是没有任何效果…

代码示例(为简单起见,更改了程序包名称)

package runnableProject.application;

import runnableProject.application.configuration.ServerConfigurationReference.class
import com.myProject.customLibrary.SharedReference.class

//@SpringBootApplication(scanBasePackages = {"com.myProject.customLibrary", "runnableProject.configuration"}) 
//@EnableJpaRepositories("com.myProject.customLibrary")

@SpringBootApplication(scanBasePackageClasses = {SharedReference.class, ServerConfigurationReference.class})   
public class MyApplication {

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

}

库中的类:

package com.myProject.customLibrary.configuration;

import com.myProject.customLibrary.configuration.UserRepository.class;

@Service
public class CustomUserDetailsService implements UserDetailsService {
    private UserRepository userRepository;

    @Autowired
    public CustomUserDetailsService(UserRepository userRepository) {
        this.userRepository = userRepository;       
    }
...

package myProject.customLibrary.configuration;

@Repository
public interface UserRepository extends CustomRepository<User> {
    User findByLoginAndStatus(String var1, Status var2);

    ...
}

阅读 361

收藏
2020-05-30

共1个答案

小编典典

刚刚找到解决方案。我没有定义要从单独的库进行扫描的基本包,而是仅在该库中创建了带有全部注释的配置类,并将其导入到我的主MyApplication.class中:

package runnableProject.application;

import com.myProject.customLibrary.configuration.SharedConfigurationReference.class

@SpringBootApplication
@Import(SharedConfigurationReference.class)
public class MyApplication {

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

}



package com.myProject.customLibrary.configuration;

@Configuration
@ComponentScan("com.myProject.customLibrary.configuration")
@EnableJpaRepositories("com.myProject.customLibrary.configuration.repository")
@EntityScan("com.myProject.customLibrary.configuration.domain")
public class SharedConfigurationReference {}
2020-05-30