spring-data-jpa SpringBoot:无法自动连接来自其他Jar库的类

watbbzwu  于 2022-11-10  发布在  Spring
关注(0)|答案(4)|浏览(158)

我正在开发一个SpringBoot应用程序(例如MyApp),它依赖于两个具有不同实现的数据项目:
data-jdbc.jar

  • 使用spring-boot-starter-jdbc构建,它公开了应用程序将使用的JDBCDataService类

样本代码:

@Service 
public class JDBCDataServiceImpl implements JDBCDataService {

@Autowired
private JDBCDataRepository jdbcDataRepository;    
... 
}
  • 带封装my.data.jdbc
  • 没有SpringBoot主类。Spring配置仅为单元测试类创建
  • 存储库类使用JDBCTemplate

示例存储库:

@Repository
public class JDBCDataRepositoryImpl implements JDBCDataRepository {

@Autowired
protected JdbcTemplate jdbcTemplate;
...
}

data-jpa.jar

  • 使用spring-boot-starter-data-jpa构建,spring-boot-starter-data-jpa还公开了我的应用程序也将使用的JPADataService类

样本代码:

@Service 
public class JPADataServiceImpl implements JPADataService {

@Autowired
private JPADataRepository jpaDataRepository;    
... 
}
  • 带有封装my.data.jpa
  • 没有SpringBoot主类。Spring配置仅为单元测试类创建
  • 存储库类扩展了CrudRepository接口

示例存储库:

@Repository
public interface JPADataRepository extends CrudRepository<MyObject, Integer{
...
}

在我的SpringBoot项目中,我有以下SpringBoot主应用程序:

@SpringBootApplication
public class MyApp extends SpringBootServletInitializer {
}

在我的业务服务MainService类中,我有以下注入

@Service
public class MainServiceImpl implements MainService {

@Autowired
private JDBCDataService jdbcDataService;

@Autowired
private JPADataService jpaDataService;

然而,我遇到了"Could not Autowire. No beans of 'JPADataService' type found"问题,它只存在于JPADataService类中,但在JDBCService类中运行良好。
我已经尝试了以下问题中的解决方案,但这些方案都不适用于我的情况:
Can't I @Autowire a Bean which is present in a dependent Library Jar?

@ComponentScan(basePackages = {"org.example.main", "package.of.user.class"})

How can I @Autowire a spring bean that was created from an external jar?

@Configuration
@ComponentScan("com.package.where.my.class.is")
class Config {
...
}

我现在已经找到了解决我的问题的方法。我必须把我的主wwwiderexampleidercom向上移动MyApp.java一个包级别,以便扫描我的数据库。
为了成功地扫描带有my.data.jpamy.data.jdbc包的库,我不得不将MyApp.java放在my.app包下,而不是将它移到my下。

vi4fp9gy

vi4fp9gy1#

我现在已经找到了解决我的问题的方法。我必须把我的主wwwiderexampleidercom向上移动MyApp.java一个包级别,以便扫描我的数据库。
为了成功扫描带有my.data.jpamy.data.jdbc包的库,我不得不将MyApp.java放在my.app包下,而不是放在my包下。

lh80um4z

lh80um4z2#

如果你试图自动连接的类没有用@Component注解,那么添加@ComponentScan就不起作用。为了使它起作用,你必须在你的@Configuration类中注解一个方法。类似这样的东西应该可以让你自动连接类:

@Configuration
public class ConfigClass{

    @Bean
    public JPADataService jpaDataService(){
        return new JPADataService();
    }
}
siv3szwd

siv3szwd3#

您需要在外部jar中配置spring.factories

external-jar-project
   |--java
   |--resources
        |-- META-INF
              |-- spring.factories

Spring的内容。

org.springframework.boot.autoconfigure.EnableAutoConfiguration=xxx
rxztt3cl

rxztt3cl4#

这个问题也困扰了我很长时间,我发现的是springboot无法扫描你介绍的jar包路径下的相关类。
您可能需要使用@EnableJpaRepositories(“cn.XXX”)@EntityScan(“cn.XXX”)之类的注解来扫描您的类)

相关问题