springboot A项目下有两个子项目B和C,现B依赖C,并在pom引入C,现使用C中的类时遇坑,这里会存在两个问题
问题1、编译不能过
解决办法:
B和C各自都使用了springboot的打包插件,所以B无法引入C,此时去除C中的springboot打包插件或者改用Maven打包插件,注意
<build>
<plugins>
<!--被引入的spring boot jar 包不能引入此plugin ,否则引入此jar包的项目编译时会报 找不到程序包 的错误-->
<!--<plugin>-->
<!--<groupId>org.springframework.boot</groupId>-->
<!--<artifactId>spring-boot-maven-plugin</artifactId>-->
<!--</plugin>-->
</plugins>
</build
或者改成
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
问题2:能编译了,但启动项目B时报错,dao层中的repository或实体没有找到。
org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.cws.web.dao.ClientRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1493)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1104)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066)
解决办法:
加入
@EnableJpaRepositories("加入C项目Repositories的目录")
@EntityScan("加入C项目实体的目录")
(也可用@ComponentScan:会自动扫描指定包下的全部标有@Component的类,并注册成bean,当然包括@Component下的子注解@Service,@Repository,@Controller。并且后面扫描目录的*号不能少)
个人猜想,可能是jpa默认找到是B项目中的Repositories和entity,而引入的C项目中的不会去扫,需要手动加入C项目对应的目录。纯属猜想,大神勿喷。
最后贴一张项目结构。