Spring Boot开发时遇到的一系列问题及解决办法总结

问题一

Spring Boot扫描包提示找不到mapper的问题,异常信息内容:

Consider defining a bean of type in your configuration

分析原因:Spring Boot项目的Bean装配默认规则是根据Application类所在的包位置从上往下扫描,“Application类”是指Spring Boot项目入口类。如果Application类所在的包为:com.yoodb.blog,则只会扫描com.yoodb.blog包及其所有子包,如果service或dao所在包不在com.yoodb.blog及其子包下,则不会被扫描。

解决方法:

方式一:使用注解@ComponentScan(value=”com.yoodb.blog”),其中,com.yoodb.blog为包路径。

方式二:将启动类Application放在上一级包中,注意的是Application启动类必须要保证在包的根目录下。

问题二

启动Spring Boot时,,抛出异常信息如下:

Your ApplicationContext is unlikely to start due to a @ComponentScan of the default package

application.Java类文件内容如下:

import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.boot.SpringApplication;
@Controller
@SpringBootApplication
@Configuration
public class HelloApplication {
    @RequestMapping("hello")
    @ResponseBody
    public String hello() {
        return "hello world!";
    }
    public static void main(String[] args) {
        SpringApplication.run(HelloApplication.class, args);
    }
}

分析原因:Spring Boot启动时,抛出“** WARNING ** : Your ApplicationContext is unlikely to start due to a @ComponentScan of the default package.”警告信息,这是由于application.Java文件不能直接放在main/java文件夹下,必须要建一个包把它放进去。

解决办法:Spring Boot在写启动类的时候如果不使用@ComponentScan指明对象扫描范围,默认指扫描当前启动类所在的包里的对象,如果当前启动类没有包,则在启动时会抛出上述警告信息,导致项目出错。  

问题三

Spring Boot连接数据库时,抛出异常信息如下:

caused by: java.lang.NoClassDefFoundError: javassist/bytecode/ClassFile

分析原因:这是由于缺少javassist.jar包导致启动失败

解决办法:通过Eclipse执行Maven命令重构项目:Maven-Update Project,等待下载jar包即可,若还是失败请手动添加javassist.jar包的pom.xml配置信息。

Spring Boot使用spring-data-jpa插件,抛出异常信息如下:

caused by: java.lang.illegalargumentexception: Not a managed type: class entity.User

分析原因:这是由于Spring Boot未找到实体对象指定的类名,缺少jpa entity配置路径

解决办法:在Repository配置类前面添加注解@EntityScan('entity对应的包路径')

问题四

Spring Boot返回json字符串,增加APPLICATION_JSON参数代码如下:

mvc.perform(MockMvcRequestBuilders.get("/hello").accept(MediaType.APPLICATION_JSON))

在添加APPLICATION_JSON参数后,抛出“APPLICATION_JSON cannot be resolved or is not a field”异常信息。

分析原因: Bean实体中存在getXsetX方法,但是没有这个x属性,将导致json转换失败,抛出“APPLICATION_JSON cannot be resolved or is not a field”异常信息。

解决办法:去掉不存在属性的getXsetX方法或者增加上改属性即可。

猜你喜欢

转载自yq.aliyun.com/articles/621681