gpt4 book ai didi

spring-boot - Spring 启动 : autowire beans from library project

转载 作者:行者123 更新时间:2023-12-03 21:06:15 25 4
gpt4 key购买 nike

我正在努力从使用 gradle 导入的自定义库中 Autowiring bean。
在阅读了几个类似的主题后,我仍然无法找到解决方案。
我有一个依赖于另一个项目的 Spring Boot 项目(我的带有组件、存储库等的自定义库)。这个库是一个 Spring 不可运行的 jar,主要由域实体和存储库组成。它没有可运行的 Application.class 和任何属性...
当我启动应用程序时,我可以看到我的“CustomUserService”bean(来自库)正在尝试初始化,但其中 Autowiring 的 bean 无法加载(接口(interface) UserRepository)......
错误:

Parameter 0 of constructor incom.myProject.customLibrary.configuration.CustomUserDetailsServicerequired a bean of type'com.myProject.customLibrary.configuration.UserRepository' that could notbe found.


我什至尝试设置'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);

...
}

最佳答案

刚刚找到解决方案。
我没有定义要从单独的库中扫描的基本包,而是在这个库中创建了带有大量注释的配置类,并将其导入到我的主 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 {}

关于spring-boot - Spring 启动 : autowire beans from library project,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41815871/

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