Spring boot controller类加入@Autowired注解启动报错

图片说明 工程结构

//下面是全部的代码,最下面时错误日志。第一次提问,不知道插入代码片的格式是不是这样的,跪求大神指导,已经看了很多解决方案,但都无法解决我的问题,注释掉Autowired或者@注释掉Autowired(required=false)虽然可以启动项目,但是程序执行时又会发生错误,问题是逃避不了的。再次跪求大神指导。


//controller
package controller;

import java.util.List;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import bean.AppMessage;
import service.AppMessageService;

@RestController
@RequestMapping("/appmessage")
public class AppMessageController {


    @Autowired/*(required=false)*/
    private AppMessageService service;


    @RequestMapping("/getThree")
    public List<AppMessage> getThreeForMessage(){

        List<AppMessage> list = service.getMessage();        
        return list;
    }

    @RequestMapping("/getAll")
    public List<AppMessage> getAllMessage(){

        List<AppMessage> list = service.getAllMessage();
        int num = list.size();
        if(null!=list && num>3){
            for (int i = 0; i < num-3; i++) {
                list.remove(0);
            }
        }
        return list;
    }

    @RequestMapping("/getByID")
    public List<AppMessage> getMessageById(@RequestParam("id") String id){
        List<AppMessage> list = service.getMessageById(id);
        int num = list.size();
        if(null!=list && num>5){
            for (int i = 0; i < num-5; i++) {
                list.remove(0);
            }
        }
        return list;
    }

    @RequestMapping(value = "/add",method = RequestMethod.POST)
    public int addMessage(@RequestBody AppMessage appMessage){
        return service.addMessage(appMessage);
    }

    @RequestMapping(value="/delMessageById",method=RequestMethod.POST)
    public int delMessageById(@RequestParam("id") String id){
            return service.delMessage(id);
    }

}

//Service
package service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import bean.AppMessage;
import mapper.AppMessageMapper;

@Transactional
@Service("appMessageService")
public class AppMessageService {

    @Autowired
    private AppMessageMapper mapper;

    public List<AppMessage> getMessage(){
         List<AppMessage> list = new ArrayList<AppMessage>();
         list.add(mapper.selectByPrimaryKey("xtt"));
         //list = mapper.selectAll();
         return list;
    }

    public List<AppMessage> getAllMessage(){
         List<AppMessage> list = new ArrayList<AppMessage>();
         list = mapper.selectAll();
         return list;
    }

    public int addMessage(AppMessage appMessage) {
        return mapper.insert(appMessage);
    }

    public List<AppMessage> getMessageById(String id) {
        return mapper.getMessById(id);
    }

    public int delMessage(String id) {
        return mapper.deleteByPrimaryKey(id);
    }
}

//Mapper 接口,映射到mapper.xml
package mapper;

import java.util.List;

import bean.AppMessage;

public interface AppMessageMapper {

    int deleteByPrimaryKey(String id);

    int insert(AppMessage record);

    int insertSelective(AppMessage record);

    AppMessage selectByPrimaryKey(String id);

    int updateByPrimaryKeySelective(AppMessage record);

    int updateByPrimaryKey(AppMessage record);

    List<AppMessage> selectAll();

    List<AppMessage> getMessById(String id);

}

<!-- Mapper.xml文件  -->
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="mapper.AppMessageMapper" > <!-- 对应mapper接口的位置 -->

  <resultMap id="BaseResultMap" type="bean.AppMessage" >
    <id column="id" property="id" jdbcType="VARCHAR" />
    <result column="message" property="message" jdbcType="VARCHAR" />
    <result column="senddate" property="senddate" jdbcType="TIMESTAMP" />
  </resultMap>

  <sql id="Base_Column_List" >
    id, message, senddate
  </sql>
  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.String" >
    select 
    <include refid="Base_Column_List" />
    from appuser_message
    where id = #{id,jdbcType=VARCHAR}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.String" >
    delete from appuser_message
    where id = #{id,jdbcType=VARCHAR}
  </delete>
  <insert id="insert" parameterType="bean.AppMessage" >
    insert into appuser_message (id, message, senddate
      )
    values (#{id,jdbcType=VARCHAR}, #{message,jdbcType=VARCHAR}, #{senddate,jdbcType=TIMESTAMP}
      )
  </insert>
  <insert id="insertSelective" parameterType="bean.AppMessage" >
    insert into appuser_message
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="id != null" >
        id,
      </if>
      <if test="message != null" >
        message,
      </if>
      <if test="senddate != null" >
        senddate,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="id != null" >
        #{id,jdbcType=VARCHAR},
      </if>
      <if test="message != null" >
        #{message,jdbcType=VARCHAR},
      </if>
      <if test="senddate != null" >
        #{senddate,jdbcType=TIMESTAMP},
      </if>
    </trim>
  </insert>
  <update id="updateByPrimaryKeySelective" parameterType="bean.AppMessage" >
    update appuser_message
    <set >
      <if test="message != null" >
        message = #{message,jdbcType=VARCHAR},
      </if>
      <if test="senddate != null" >
        senddate = #{senddate,jdbcType=TIMESTAMP},
      </if>
    </set>
    where id = #{id,jdbcType=VARCHAR}
  </update>
  <update id="updateByPrimaryKey" parameterType="bean.AppMessage" >
    update appuser_message
    set message = #{message,jdbcType=VARCHAR},
      senddate = #{senddate,jdbcType=TIMESTAMP}
    where id = #{id,jdbcType=VARCHAR}
  </update>

  <select id="selectAll" resultMap="BaseResultMap">
    select 
         id, message, senddate
    from appuser_message
    order by senddate
  </select>

  <select id="getMessById" resultMap="BaseResultMap" parameterType="java.lang.String">
   select 
           id, message, senddate
   from 
        appuser_message  
       where id = #{id,jdbcType=VARCHAR}
    order by senddate asc  
  </select>

</mapper>
//实体类
package bean;

import java.util.Date;

public class AppMessage {

    private String id;

    private String message;

    private Date senddate;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id == null ? null : id.trim();
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message == null ? null : message.trim();
    }

    public Date getSenddate() {
        return senddate;
    }

    public void setSenddate(Date senddate) {
        this.senddate = senddate;
    }

}

//启动类
package com.shuai.spring_boot_1;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

/**
 * Hello world!
 *
 */
@ComponentScan(basePackages="controller")
@SpringBootApplication
public class App {

    public static void main(String[] args) {

        SpringApplication.run(App.class, args);
    }
}

pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.3.5.RELEASE</version>
    </parent>

    <groupId>com.shuai</groupId>
    <artifactId>spring-boot-1</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>spring-boot-1</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>

        <!--web应用基本环境配置 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.jayway.jsonpath</groupId>
            <artifactId>json-path</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.0.0</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

        <!-- <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> 
            <version>1.3.5.RELEASE</version> </dependency> -->

    </dependencies>

    <build>
        <plugins>
            <!-- spring-boot-maven-plugin插件就是打包spring boot应用的 -->
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

#properties文件   

spring.datasource.url=jdbc:mysql://localhost:3306/world
spring.datasource.username=root
spring.datasource.password=000000
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.max-idle=10
spring.datasource.max-wait=10000
spring.datasource.min-idle=5
spring.datasource.initial-size=5

server.port=8012
server.session.timeout=10
server.tomcat.uri-encoding=UTF-8


# mybatis.config= classpath:mybatis-config.xml
mybatis.mapperLocations=classpath:mappers/*.xml
# domain object's package 
#mybatis.typeAliasesPackage=com.lgp.SpringBoot.bean
mybatis.typeAliasesPackage=bean
# handler's package
# mybatis.typeHandlersPackage=
# check the mybatis configuration exists
# mybatis.check-config-location= 
# mode of execution. Default is SIMPLE
# mybatis.executorType= 

图片说明 错误日志

2个回答

这类报错一般都是spring配置中包扫描的问题:<!-- 包扫描器 @Controller注解的类 -->或@Controller 和 @Service注解 以及正确包名

qq_37417648
qq_37417648 我也出现 @Autowired 注入问题,结果是包结构不对,哈哈哈
6 个月之前 回复
weixin_42081732
程 程 程序员 spring boot 我搭的这个项目只有。properties这一个配置文件,是我的配置文件少了吗
一年多之前 回复

你的启动类上加了 @ComponentScan(basepackage="controller") , 导致其只能将这个包下的带有@Controller,@Service , @Component,@Repostory注解的类注入到IOC
所以找不到AppMessageSevice这个bean

weixin_42081732
程 程 程序员 回复农夫丶果园: 找到原因了,根本就不是什么注入不注入bean,bean找不到的原因,和spring配置没有关系,想想也是,springboot本来就不需要自己去写spring的配置以及一些其他的配置,这也正是它的一大优点。真正的原因是1.我最开始的确实没扫描到service类。2.后来扫描到了却还是启动报错,为什么呢,因为我他妈的mapper.xml文件,也就是写sql语句的地方出现了问题,字段id数据库是int,我的配置文件是VARCHAR,这一点我昨天就发现了,也改了,但是没有改完全,还剩了一两个没有改,问题就出在这,这才是最根本的原因。这个问题我也不是第一次碰到了,在我还在用springmvc+mybatis的时候就碰到过一样的问题,当时真是一看到Error Creating bean....就条件反射一样去找自己mapper.xml的错误,可能换了个框架我就没想那么多,浪费了好多时间,真想给自己两巴掌,好在问题还是解决了
一年多之前 回复
qq_38167579
农夫丶果园 回复weixin_42081732: 我还是建议你把 springboot 的启动类 ,放在最外层 ; 其他类要么放在与他同级 , 要么在同级中建立其他包放进去
一年多之前 回复
qq_38167579
农夫丶果园 回复weixin_42081732: 把错误日志拉到最右边,看看是不是AppMessageService里面注入的mapper找不到
一年多之前 回复
weixin_42081732
程 程 程序员 纠正一下,我没将service类放到启动类同级,而是放到了controller包下
一年多之前 回复
weixin_42081732
程 程 程序员 启动类在可以扫描与它在同级的类与@ComponentScan注释声明的包下的类,然后我之前试过将 service类 移动到与启动类同级,虽然service类被扫描到了(真扫描到了,类上多了一个S) ,但是依然报同样的错误。
一年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐