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个回答

你的启动类上加了 @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的错误,可能换了个框架我就没想那么多,浪费了好多时间,真想给自己两巴掌,好在问题还是解决了
10 个月之前 回复
qq_38167579
农夫丶果园 回复weixin_42081732: 我还是建议你把 springboot 的启动类 ,放在最外层 ; 其他类要么放在与他同级 , 要么在同级中建立其他包放进去
10 个月之前 回复
qq_38167579
农夫丶果园 回复weixin_42081732: 把错误日志拉到最右边,看看是不是AppMessageService里面注入的mapper找不到
10 个月之前 回复
weixin_42081732
程 程 程序员 纠正一下,我没将service类放到启动类同级,而是放到了controller包下
10 个月之前 回复
weixin_42081732
程 程 程序员 启动类在可以扫描与它在同级的类与@ComponentScan注释声明的包下的类,然后我之前试过将 service类 移动到与启动类同级,虽然service类被扫描到了(真扫描到了,类上多了一个S) ,但是依然报同样的错误。
10 个月之前 回复

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

weixin_42081732
程 程 程序员 spring boot 我搭的这个项目只有。properties这一个配置文件,是我的配置文件少了吗
10 个月之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
springboot在controller中使用了autowired注解,会导致工程无法启动
报错信息如下: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'tempControllor': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.templates.service.UserService com.templates.controller.TempControllor.userService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.templates.service.UserService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} ![controller中使用了注解autowired](https://img-ask.csdn.net/upload/201705/01/1493568939_810362.png) 但是把controller里的注解去掉,service和dao中还存在autowired注解,不会影响工程正常启动 ![启动正常](https://img-ask.csdn.net/upload/201705/01/1493569310_114957.png) ![service中含有autowired注解](https://img-ask.csdn.net/upload/201705/01/1493569324_518049.png)
关于spring boot注解的使用@Autowired
今天写代码的时候,在一个controller里面。有一个service死活是注解不了。 放在其他的控制器或者类里面都没有问题。后来一点点测试,发现了问题。 先show代码: 控制器 ``` @CrossOrigin @RestController @RequestMapping(value = "api/kpi/TOperLog", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) public class TOperLogController { private Logger logger = LoggerFactory.getLogger(this.getClass()); private static final String TITLE = "OperLog"; private static final String TRUE = "true"; private static final String FALSE = "false"; @Autowired private TOperationlogService sysLogService; @AOPHandler(value = "查询") @GetMapping("/querylogbyid/{objectId}") public String querylogbyid(HttpServletRequest request, @PathVariable Integer objectId) { TOperationlogEntity obj = sysLogService.QueryOperLogById(1); return JSON.toJSONString(obj); } /** * 查询日志类型集合 * * @param request * @return */ @PostMapping("/QueryOperLogTypeList") private String QueryLogTypeList(HttpServletRequest request) { String requestURL = VerifyUtil.trimBaseHref(request.getRequestURL().toString()); try { List<String> list = sysLogService.QueryLogTypeList(); return RestfulTool.buildCollection(new ErrorInfo(TITLE, TRUE, JSON.toJSONString(list)), requestURL); } catch (Exception ex) { logger.error(String.format("内部服务器错误,修改积分计量规则失败: %s", ex.getMessage())); return RestfulTool.buildCollection(new ErrorInfo(TITLE, FALSE, "修改积分计量规则失败"), requestURL); } } /** * 获取操作日志 * @param request * @param type * @param page * @param pagesize * @return */ @PostMapping("/QueryOperLogList") private String QueryOperLogList(HttpServletRequest request,@RequestParam("type")String type,@RequestParam("page")Integer page, @RequestParam("pagesize")Integer pagesize){ String requestURL = VerifyUtil.trimBaseHref(request.getRequestURL().toString()); try { Pageable pageable=new PageRequest(page-1,pagesize); Page<TOperationlogEntity> pagelist= sysLogService.QueryOperLogList(type,pageable); return RestfulTool.buildCollection(new ErrorInfo(TITLE, TRUE, JSON.toJSONString(pagelist)), requestURL); } catch (Exception ex) { logger.error(String.format("内部服务器错误,获取操作日志失败: %s", ex.getMessage())); return RestfulTool.buildCollection(new ErrorInfo(TITLE, FALSE, "获取操作日志失败"), requestURL); } } } ``` 就是这个TOperationlogService 始终注解不了。经过排除法,是因为 @AOPHandler(value = "查询") 这个APO,去掉后正常注解。 百度后有人说如果有new的时候,就无法使用spring 来进行管理了。但是代码并没有new,下面是AOP的代码。里面也使用到了TOperationlogService,但是是通过注解方式。 ``` ** * 系统日志:切面处理类 */ @Aspect @Component public class SysLogAspect { @Autowired private TOperationlogService sysLogService; @Value("${tokenName}") private String tokenName; @Value("${tokenkey}") private String TokenKey; private Logger logger = LoggerFactory.getLogger(this.getClass()); //定义切点 @Pointcut //在注解的位置切入代码 @Pointcut(value = "@annotation(com.pcitc.sii.pfm.service.AOPHandler)") public void logPoinCut() { } /** * 控制器执行完成后,添加操作日志 * @param joinPoint */ @After("logPoinCut()") public void saveSysLog(JoinPoint joinPoint) { HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder .getRequestAttributes()).getRequest(); try { TOperationlogEntity oplog = new TOperationlogEntity(); //从切面织入点处通过反射机制获取织入点处的方法 MethodSignature signature = (MethodSignature) joinPoint.getSignature(); //获取切入点所在的方法 Method method = signature.getMethod(); AOPHandler myLog = method.getAnnotation(AOPHandler.class); if (myLog != null) { String value = myLog.value(); oplog.setLogDec(value);//保存获取的操作 oplog.setLogTypeCode(myLog.opertype());//操作类型 } //读取session中存储的token,从token中获取用户的信息 String tokenstr = request.getHeader(tokenName); Claims claims = JwtUtil.parseJWT(tokenstr, TokenKey); oplog.setUserName(claims.get("username").toString()); oplog.setUserId(Long.parseLong(claims.get("id").toString())); oplog.setLogDate(new Date()); sysLogService.SaveOperLog(oplog); }catch (Exception ex){ logger.error(String.format("AOP切面内部错误:{%s}",ex.getMessage()) ); } } } ``` 有人给解释下为啥会出现这个情况吗
Spring boot 项目启动因为@value报错Injection of autowired dependencies failed
## Spring boot项目启动时报错—— ## Injection of autowired dependencies failed ## ## ## Could not resolve placeholder 'owa.url' in string value "${owa.url}" ## ## ## ![图片说明](https://img-ask.csdn.net/upload/201902/28/1551351377_216263.png) ## ## ![图片说明](https://img-ask.csdn.net/upload/201902/28/1551351505_690876.png) ## ## ## 定义的owa.url是在application.properties文件当中,并木有问题 ## ## 因为@Value注解的原因, ## 但实际上是自己不小心删掉了pom.xml文件里面的一些内容, ## 其余的文件没有改动 ## ## 就是不知道是改了pom.xml文件中的那些信息了, ## 希望告知是缺少了pom.xml中的哪一部分依赖问题, ## 麻烦帮忙解决一下,谢谢!
Spring框架中的Autowired注解,默认真的是按照ByType方式实现自动注入的吗?
在学习spring IOC的过程中,接触到@Autowired注解,资料上都是说默认是按照Bytype类型实现自动注入,但我的实际操作却发现是:先使用ByName,如果失败,再使用ByType。贴代码,求指点: Student类: ``` @Component public class Student { @Value("12") int age; @Value("lisa") String name; @Autowired School school; public Student(){} public Student(int age, String name, School school) { this.age = age; this.name = name; this.school = school; } @Override public String toString() { return "Student{" + "age=" + age + ", name='" + name + '\'' + ", school=" + school + '}'; } } ``` School类: ``` public class School { String name; String address; public School() { } public School(String name, String address) { this.name = name; this.address = address; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } ``` xml文件 ``` <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!--配置注解扫描器,base-package表示注解所在的包,目的是告诉spring框架去扫描指定包的注解--> <context:component-scan base-package="com.aipande.bao1"/> <bean id="school" class="com.aipande.bao1.School"> <property name="name" value="武汉大学21"/> </bean> <bean id="school03" class="com.aipande.bao1.School"> <property name="name" value="武汉大学21"/> </bean> <bean id="school02" class="com.aipande.bao1.School"> <property name="name" value="武汉大学"/> </bean> </beans> ``` 测试类: ``` public class AppTest01 { public static void main(String[] args) { /* * 创建spring容器对象 * spring框架在加载xml文件并创建spring容器对象的同时, * 就会将xml文件中配置的bean对象(作用域为singleton)一同创建,并将这些对象放置在spring容器中。 * */ String config = "applicationContext.xml"; ApplicationContext ctx = new ClassPathXmlApplicationContext(config); //使用getBean()方法获取bean对象 Student stu = (Student) ctx.getBean("student"); System.out.println(stu); } } ``` 结果输出: ``` Student{age=12, name='lisa', school=School{name='武汉大学21', address='null'}} ``` 问题: 如果按照Bytype方式获取bean对象,那上面就应该报错啊,因为sprig容器中存在多个同源bean对象,但是没有报错,说明是按照byName的方式注入。后来我将xml文件中id为school的bean对象删除,就出现了错误提示,说明此时是按照byType的方式注入。因此我有上面的疑问,求解
spring使用JUnit时autowired报错,controller里面autowired可以的
试了好多办法还是不行,不知道哪里配错了。。麻烦大神帮看一下 异常信息: ``` SEVERE: Caught exception while allowing TestExecutionListener [org.springframework.test.context.support.DependencyInjectionTestExecutionListener@5f98de7] to prepare test instance [com.xxx.xxx.entity.UserTest@42d33bc1] org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.xxx.xxx.entity.UserTest': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.xxx.xxx.service.UserService com.xxx.xxx.entity.UserTest.service; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.xxx.xxx.service.UserService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:285) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1074) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties(AbstractAutowireCapableBeanFactory.java:374) at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:110) at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:75) at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:321) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:220) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:301) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:303) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:240) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70) at org.junit.runners.ParentRunner.run(ParentRunner.java:363) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:180) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192) Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.xxx.xxx.service.UserService com.xxx.xxx.entity.UserTest.service; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.xxx.xxx.service.UserService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:502) at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:84) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:282) ... 26 more Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.xxx.xxx.service.UserService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:920) at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:789) at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:703) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:474) ... 28 more ``` UserTest.java ``` package com.xxx.xxx.entity; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.xxx.xxx.service.UserService; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration({"classpath*:**/applicationContext.xml","classpath*:**/springmvc-servlet.xml"}) public class UserTest { @Autowired UserService service; //@Ignore @Test public void userHPTest() { System.out.println(service.get("889e4d63ff024b29a173ab52ce174cc9")); } } ``` UserServiceImpl.java(这个是service的实现) ``` package com.xxx.xxx.serviceimpl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.xxx.xxx.dao.BaseDao; import com.xxx.xxx.dao.UserDao; import com.xxx.xxx.entity.User; import com.xxx.xxx.service.UserService; @Service("userServiceImpl") public class UserServiceImpl extends BaseServiceImpl<User> implements UserService { @Autowired UserDao dao; @Override protected BaseDao<User> getDao() { return dao; } } ``` applicationContext.xml(我感觉我可能是这里不对) ``` <?xml version="1.0" encoding="UTF-8" ?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:context="http://www.springframework.org/schema/context" xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation=" http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd"> <context:component-scan base-package="com.xxx.xxx.dao"></context:component-scan> <context:component-scan base-package="com.xxx.xxx.daoimpl"></context:component-scan> <context:component-scan base-package="com.xxx.xxx.service"></context:component-scan> <context:component-scan base-package="com.xxx.xxx.serviceimpl"></context:component-scan> </beans> ``` springmvc-servlet.xml(我在controller里autowired是没有问题的) ``` <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"> <context:component-scan base-package="com.xxx.xxx.controller"></context:component-scan> <context:component-scan base-package="com.xxx.xxx.dao"></context:component-scan> <context:component-scan base-package="com.xxx.xxx.daoimpl"></context:component-scan> <context:component-scan base-package="com.xxx.xxx.service"></context:component-scan> <context:component-scan base-package="com.xxx.xxx.serviceimpl"></context:component-scan> <mvc:annotation-driven/> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/"></property> <property name="suffix" value=".jsp"></property> </bean> </beans> ```
spring boot 项目访问controller报错
搭建最基本的spring boot项目,版本是2.0.4.RELEASE。 整合mybatis, 从数据库中查询数据。 我想 通过浏览器,直接访问controller,看到json格式的数据; 但是,控制台中能看到查询的数据,接下来就报错。 Controller ``` @Controller public class UserController { @Autowired private UserService userService; @GetMapping("/findAll") @ResponseBody public List<User> findAll(){ List<User> list = userService.findAll(); System.out.println(Arrays.toString(list.toArray())); return userService.findAll(); } } ``` 访问 http://localhost:1111/findAll ![浏览器端没有显示json格式数据](https://img-ask.csdn.net/upload/201808/21/1534843529_294415.png) 控制台先显示查询出来的数据,然后报错; ``` [User{id='122221', status='1', roleId='03bd3cc782b242bbab08c464ac35b0fa', remark='监控大盘', UpdateTime=2018-08-16 15:10:27.0}, User{id='12222221', status='1', roleId='03bd3cc782b242bbab08c464ac35b0fa', remark='监控大盘', UpdateTime=2018-08-16 15:10:27.0}, User{id='yyx', status='1', roleId='yyx0101', remark='监控大盘', UpdateTime=2018-08-16 15:10:27.0}] 2018-08-21 17:03:55.089 INFO 17728 --- [a-EvictionTimer] c.n.e.registry.AbstractInstanceRegistry : Running the evict task with compensationTime 410ms 2018-08-21 17:03:55.132 ERROR 17728 --- [nio-1111-exec-8] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Handler dispatch failed; nested exception is java.lang.NoClassDefFoundError: com/fasterxml/jackson/module/jaxb/JaxbAnnotationIntrospector] with root cause java.lang.ClassNotFoundException: com.fasterxml.jackson.module.jaxb.JaxbAnnotationIntrospector ``` 按照之前的想法,加上了@ResponseBody 注解后,方法返回的数据应该被springboot内置的jackson,转换成了json格式的数据, 然后浏览器端直接显示的。 不知道问题出在哪里?
spring boot中@autowired不起作用问题
spring boot项目,是由多个Module组成的,我的rcreport模块的main方法里要调用ws模块里的service类方法,用@autowired不起作用,哪位大神帮解决一下.如下图: ![图片说明](https://img-ask.csdn.net/upload/201709/20/1505870329_484459.jpg) ![图片说明](https://img-ask.csdn.net/upload/201709/20/1505870434_703941.png) ![图片说明](https://img-ask.csdn.net/upload/201709/20/1505870441_901921.png)
调用dubbo调用其他工程的服务接口 , 打上@Autowired注解启动时报下面的错 ,求大神们帮忙?
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'voucherService': Unsatisfied dependency expressed through field 'tradeOrdersService'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'tradeOrdersService': FactoryBean threw exception on object creation; nested exception is java.lang.IllegalStateException: No such extension com.alibaba.dubbo.rpc.ProxyFactory by name tccJavassist at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:596) ~ [spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE] at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:90) ~[spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE] at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:374) ~[spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1378) ~[spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:575) ~[spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:498) ~[spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE] at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) ~[spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE] at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE] at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) ~[spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE] at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE] at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:846) ~[spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE] at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:863) ~[spring-context-5.1.2.RELEASE.jar:5.1.2.RELEASE] at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:546) ~[spring-context-5.1.2.RELEASE.jar:5.1.2.RELEASE] at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:140) ~[spring-boot-2.1.0.RELEASE.jar:2.1.0.RELEASE] at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:775) [spring-boot-2.1.0.RELEASE.jar:2.1.0.RELEASE] at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397) [spring-boot-2.1.0.RELEASE.jar:2.1.0.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:316) [spring-boot-2.1.0.RELEASE.jar:2.1.0.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1260) [spring-boot-2.1.0.RELEASE.jar:2.1.0.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1248) [spring-boot-2.1.0.RELEASE.jar:2.1.0.RELEASE] at com.otocenter.otocenterservice.OtoCenterServiceApplication.main(OtoCenterServiceApplication.java:14) [classes/:na] Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'tradeOrdersService': FactoryBean threw exception on object creation; nested exception is java.lang.IllegalStateException: No such extension com.alibaba.dubbo.rpc.ProxyFactory by name tccJavassist at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.doGetObjectFromFactoryBean(FactoryBeanRegistrySupport.java:178) ~[spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE] at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.getObjectFromFactoryBean(FactoryBeanRegistrySupport.java:101) ~[spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE] at org.springframework.beans.factory.support.AbstractBeanFactory.getObjectForBeanInstance(AbstractBeanFactory.java:1647) ~[spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.getObjectForBeanInstance(AbstractAutowireCapableBeanFactory.java:1216) ~[spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE] at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:257) ~[spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE] at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE] at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:273) ~[spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE] at org.springframework.beans.factory.support.DefaultListableBeanFactory.addCandidateEntry(DefaultListableBeanFactory.java:1462) ~[spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE] at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1419) ~[spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE] at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1202) ~[spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE] at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1166) ~[spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE] at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:593) ~[spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE] ... 19 common frames omitted Caused by: java.lang.IllegalStateException: No such extension com.alibaba.dubbo.rpc.ProxyFactory by name tccJavassist at com.alibaba.dubbo.common.extension.ExtensionLoader.findException(ExtensionLoader.java:494) ~[dubbo-2.5.3.jar:2.5.3] at com.alibaba.dubbo.common.extension.ExtensionLoader.createExtension(ExtensionLoader.java:501) ~[dubbo-2.5.3.jar:2.5.3] at com.alibaba.dubbo.common.extension.ExtensionLoader.getExtension(ExtensionLoader.java:319) ~[dubbo-2.5.3.jar:2.5.3] at com.alibaba.dubbo.rpc.ProxyFactory$Adpative.getProxy(ProxyFactory$Adpative.java) ~[na:2.5.3] at com.alibaba.dubbo.config.ReferenceConfig.createProxy(ReferenceConfig.java:426) ~[dubbo-2.5.3.jar:2.5.3] at com.alibaba.dubbo.config.ReferenceConfig.init(ReferenceConfig.java:300) ~[dubbo-2.5.3.jar:2.5.3] at com.alibaba.dubbo.config.ReferenceConfig.get(ReferenceConfig.java:138) ~[dubbo-2.5.3.jar:2.5.3] at com.alibaba.dubbo.config.spring.ReferenceBean.getObject(ReferenceBean.java:65) ~[dubbo-2.5.3.jar:2.5.3] at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.doGetObjectFromFactoryBean(FactoryBeanRegistrySupport.java:171) ~ [spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE] ... 30 common frames omitted
springboot抽象类中注入实例,使用@Autowired注解托管实例,注入实例为空获取不到值的问题。
https://blog.csdn.net/loney_wolf/article/details/103505788 以上博客对springboot抽象类无法注入实例化做了解决,虽然解决了抽象类注入实体为空的情况,但是不知具体解决原理是什么。 </br> </br> </br> 抽象类不能实例化,因此在抽象类中不能注入其他实例,因为无法被spring托管。然而对抽象类的子类进行实例化托管之后,抽象类中进行注入托管的实例却能正正常注入,这是为什么(个人定位是java多态的向上向下转型)
spring boot项目gralde启动报错:Could not resolve placeholder
Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder
springboot+kotlin 使用@autowired 注解失败
学习kotlin时候,遇到注解失败。在注解dao的时候一直报错 报错信息如下: ``` Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled. 2019-01-09 10:24:45.346 ERROR 13448 --- [ restartedMain] o.s.boot.SpringApplication : Application run failed org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'appController': Unsatisfied dependency expressed through field 'appService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'appService': Unsatisfied dependency expressed through field 'appDao'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.cgs.hb.dao.AppDao' 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.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:596) ~[spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE] at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:90) ~[spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE] at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:374) ~[spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1378) ~[spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:575) ~[spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:498) ~[spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE] at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) ~[spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE] at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE] at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) ~[spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE] at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE] at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:846) ~[spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE] at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:863) ~[spring-context-5.1.2.RELEASE.jar:5.1.2.RELEASE] at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:546) ~[spring-context-5.1.2.RELEASE.jar:5.1.2.RELEASE] at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:140) ~[spring-boot-2.1.0.RELEASE.jar:2.1.0.RELEASE] at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:775) [spring-boot-2.1.0.RELEASE.jar:2.1.0.RELEASE] at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397) [spring-boot-2.1.0.RELEASE.jar:2.1.0.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:316) [spring-boot-2.1.0.RELEASE.jar:2.1.0.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1260) [spring-boot-2.1.0.RELEASE.jar:2.1.0.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1248) [spring-boot-2.1.0.RELEASE.jar:2.1.0.RELEASE] at com.cgs.hb.DemoApplicationKt.main(DemoApplication.kt:20) [classes/:na] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_181] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_181] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_181] at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_181] at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) [spring-boot-devtools-2.1.0.RELEASE.jar:2.1.0.RELEASE] Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'appService': Unsatisfied dependency expressed through field 'appDao'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.cgs.hb.dao.AppDao' 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.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:596) ~[spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE] at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:90) ~[spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE] at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:374) ~[spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1378) ~[spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:575) ~[spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:498) ~[spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE] at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) ~[spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE] at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE] at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) ~[spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE] at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE] at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:273) ~[spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE] at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1239) ~[spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE] at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1166) ~[spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE] at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:593) ~[spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE] ... 24 common frames omitted Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.cgs.hb.dao.AppDao' 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:1646) ~[spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE] at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1205) ~[spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE] at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1166) ~[spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE] at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:593) ~[spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE] ... 37 common frames omitted ``` 贴上代码: pom.xml如下: ``` <?xml version="1.0" encoding="UTF-8"?> <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>2.1.0.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.example</groupId> <artifactId>app</artifactId> <version>0.0.1-SNAPSHOT</version> <name>app</name> <description>App project for Spring Boot</description> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> <kotlin.version>1.2.71</kotlin.version> <authox-starter.version>1.0.9-beta</authox-starter.version> <hibernate.version>5.2.1.Final</hibernate.version> <dc-client-starter.version>1.1.9</dc-client-starter.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-pool2</artifactId> </dependency> <dependency> <groupId>com.fasterxml.jackson.module</groupId> <artifactId>jackson-module-kotlin</artifactId> </dependency> <dependency> <groupId>org.jetbrains.kotlin</groupId> <artifactId>kotlin-reflect</artifactId> </dependency> <dependency> <groupId>org.jetbrains.kotlin</groupId> <artifactId>kotlin-stdlib-jdk8</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.7.0</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.7.0</version> </dependency> <dependency> <groupId>QRCode</groupId> <artifactId>QRCode</artifactId> <version>3.0</version> </dependency> <dependency> <groupId>commons-net</groupId> <artifactId>commons-net</artifactId> <version>3.6</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> </dependency> </dependencies> <build> <sourceDirectory>${project.basedir}/src/main/kotlin</sourceDirectory> <testSourceDirectory>${project.basedir}/src/test/kotlin</testSourceDirectory> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> <plugin> <groupId>org.jetbrains.kotlin</groupId> <artifactId>kotlin-maven-plugin</artifactId> <configuration> <args> <arg>-Xjsr305=strict</arg> </args> <compilerPlugins> <plugin>spring</plugin> <plugin>jpa</plugin> </compilerPlugins> </configuration> <dependencies> <dependency> <groupId>org.jetbrains.kotlin</groupId> <artifactId>kotlin-maven-allopen</artifactId> <version>${kotlin.version}</version> </dependency> <dependency> <groupId>org.jetbrains.kotlin</groupId> <artifactId>kotlin-maven-noarg</artifactId> <version>${kotlin.version}</version> </dependency> </dependencies> </plugin> </plugins> </build> </project> ``` 实体类 ``` package com.cgs.hb.base import javax.persistence.Entity import javax.persistence.GeneratedValue import javax.persistence.GenerationType import javax.persistence.Id import javax.persistence.Table @Entity @Table(name = "app_info") data class AppInfos( @Id @GeneratedValue(strategy=GenerationType.AUTO) var id: Long?, var fileSize: String?, var filePath: String?, var fileName: String?, var version: String?, var uploadTime: String? ) { constructor() : this(null, null, null, null, null, null) } ``` dao ``` package com.cgs.hb.dao import com.cgs.hb.base.AppInfos import org.springframework.data.jpa.repository.JpaRepository import org.springframework.stereotype.Repository @Repository interface AppDao : JpaRepository<AppInfos, Long> { fun findByVersion(v: String): List<AppInfos> } ``` service ``` package com.cgs.hb.service import com.cgs.hb.base.AppInfos import com.cgs.hb.dao.AppDao import org.springframework.beans.factory.annotation.Autowired import org.springframework.stereotype.Service import javax.transaction.Transactional @Service("appService") @Transactional class AppService { @Autowired lateinit var appDao: AppDao fun saveInfo() { var app = AppInfos(1, "1MB", "c:\\app", "test.app","1.0.0","2018-12-01") appDao.save(app) } } ``` ``` package com.cgs.hb.controller import com.cgs.hb.service.AppService import io.swagger.annotations.Api import io.swagger.annotations.ApiOperation import org.springframework.beans.factory.annotation.Autowired import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RestController @RestController @RequestMapping("/appInfo") @Api(description = "app") class AppController { @Autowired private lateinit var appService: AppService @GetMapping(value = "/saveInfo") @ApiOperation(value = "保存信息") fun saveInfo() { appService.saveInfo() } } ``` 增加启动类: ``` package com.cgs.hb import org.springframework.boot.SpringApplication import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration import org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration import org.springframework.cache.annotation.EnableCaching import org.springframework.data.jpa.repository.config.EnableJpaRepositories import org.springframework.scheduling.annotation.EnableScheduling import springfox.documentation.swagger2.annotations.EnableSwagger2 @SpringBootApplication(exclude = arrayOf(DataSourceAutoConfiguration::class, LiquibaseAutoConfiguration::class, HibernateJpaAutoConfiguration::class)) @EnableSwagger2 @EnableCaching @EnableScheduling class DemoApplication fun main(args: Array<String>) { SpringApplication.run(DemoApplication::class.java,*args) } ``` 代码结构: ![图片说明](https://img-ask.csdn.net/upload/201901/09/1547001180_732840.png) 各位大佬麻烦帮忙看下!!!
Spring Boot启动报错ERROR 3644 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :
##报错类型: ###Field xxxDao in xxxServiceImpl required a bean of type xxx that could not be found. 详细情况如下: ```java . ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v2.0.2.RELEASE) 2019-07-19 10:45:06.433 INFO 3644 --- [ main] com.meituan.hotel.Application : Starting Application on LAPTOP-2N82SD03 with PID 3644 (E:\CodeCache\IDEA\Webmagic\meituan-crawler-hotel\target\classes started by 三寸旧城七寸执念 in E:\CodeCache\IDEA\Webmagic\meituan-crawler-hotel) 2019-07-19 10:45:06.435 INFO 3644 --- [ main] com.meituan.hotel.Application : No active profile set, falling back to default profiles: default 2019-07-19 10:45:06.472 INFO 3644 --- [ main] ConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@197d671: startup date [Fri Jul 19 10:45:06 CST 2019]; root of context hierarchy 2019-07-19 10:45:07.211 INFO 3644 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http) 2019-07-19 10:45:07.229 INFO 3644 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat] 2019-07-19 10:45:07.229 INFO 3644 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.31 2019-07-19 10:45:07.232 INFO 3644 --- [ost-startStop-1] o.a.catalina.core.AprLifecycleListener : Loaded APR based Apache Tomcat Native library [1.2.21] using APR version [1.6.5]. 2019-07-19 10:45:07.232 INFO 3644 --- [ost-startStop-1] o.a.catalina.core.AprLifecycleListener : APR capabilities: IPv6 [true], sendfile [true], accept filters [false], random [true]. 2019-07-19 10:45:07.232 INFO 3644 --- [ost-startStop-1] o.a.catalina.core.AprLifecycleListener : APR/OpenSSL configuration: useAprConnector [false], useOpenSSL [true] 2019-07-19 10:45:07.235 INFO 3644 --- [ost-startStop-1] o.a.catalina.core.AprLifecycleListener : OpenSSL successfully initialized [OpenSSL 1.1.1a 20 Nov 2018] 2019-07-19 10:45:07.351 INFO 3644 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext 2019-07-19 10:45:07.351 INFO 3644 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 882 ms 2019-07-19 10:45:07.459 INFO 3644 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Servlet dispatcherServlet mapped to [/] 2019-07-19 10:45:07.462 INFO 3644 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*] 2019-07-19 10:45:07.462 INFO 3644 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*] 2019-07-19 10:45:07.462 INFO 3644 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*] 2019-07-19 10:45:07.462 INFO 3644 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*] 2019-07-19 10:45:07.490 WARN 3644 --- [ main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'hotelInfoServiceImpl': Unsatisfied dependency expressed through field 'hotelInfoDao'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.meituan.hotel.Dao.HotelInfoDao' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} 2019-07-19 10:45:07.492 INFO 3644 --- [ main] o.apache.catalina.core.StandardService : Stopping service [Tomcat] 2019-07-19 10:45:07.504 INFO 3644 --- [ main] ConditionEvaluationReportLoggingListener : Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled. 2019-07-19 10:45:07.573 ERROR 3644 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPLICATION FAILED TO START *************************** Description: Field hotelInfoDao in com.meituan.hotel.Service.impl.HotelInfoServiceImpl required a bean of type 'com.meituan.hotel.Dao.HotelInfoDao' that could not be found. Action: Consider defining a bean of type 'com.meituan.hotel.Dao.HotelInfoDao' in your configuration. Process finished with exit code 1 ``` ### 最近网项目里面加了个模块,模块是基于gradle的工程,我本身的工程是基于maven的,没有导成功,我就把那个模块删除掉了,但是运行就出问题了,网上搜了很多,但是我的注解都加了,而且目录结构也没有问题,Application.class也的确在包的最外层。 ## 希望有大佬帮忙解答一下
关于@autowired注解, 求助求助
在controller中有 @autowired private IService service; 在service中有 @autowired private IDao dao; 我的问题是: 两个之中都有@autowired, 那么哪一个先起作用; 为什么? 我自己测的时候,发现应该是controller中的先起作用; 才去遍历注入的service中的dao ; 如果没有controller, 那么dao将空指针
对某个interface,在调用的地方@Autowired,为何不会报错?
# 问题: // UserDao.java文件中,UserDao是一个interface而不是一个实例,为何UserConter.java文件中@Autowired不会报错? # 1. 项目 [netgloo](https://github.com/netgloo/spring-boot-samples/tree/master/spring-boot-mysql-springdatajpa-hibernate/src/main/java/netgloo "") # 2. 代码 models/UserDao.java ``` @Transactional public interface UserDao extends CrudRepository<User, Long> { /** * Return the user having the passed email or null if no user is found. * * @param email the user email. */ public User findByEmail(String email); } // class UserDao ``` controllers/UserController.java ``` @Controller public class UserController { ... // ------------------------ // PRIVATE FIELDS // ------------------------ @Autowired // UserDao.java文件中,UserDao是一个interface而不是一个实例,为何这里@Autowired不会报错? private UserDao userDao; } ```
dubbo spring boot spring-data-jpa报错
当有多个service实现类注入同一个Repository时,就报下面的错: ``` Caused by: java.lang.IllegalArgumentException: Repository interface must not be null on initialization! at org.springframework.util.Assert.notNull(Assert.java:115) ~[spring-core-4.3.2.RELEASE.jar:4.3.2.RELEASE] at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.initAndReturn(RepositoryFactoryBeanSupport.java:263) ~[spring-data-commons-1.12.2.RELEASE.jar:na] at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.getObject(RepositoryFactoryBeanSupport.java:213) ~[spring-data-commons-1.12.2.RELEASE.jar:na] at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.getObject(RepositoryFactoryBeanSupport.java:50) ~[spring-data-commons-1.12.2.RELEASE.jar:na] at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.doGetObjectFromFactoryBean(FactoryBeanRegistrySupport.java:168) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE] ... 255 common frames omitted ``` 1、可以正常启动的情况 ``` @Service(version = "1.0.0") public class EmployeeAccountServiceImpl implements EmployeeAccountService { @Autowired EmployeeRepository employeeRepository; ``` 2、不能正常启动的情况 ``` @Service(value = "employeeAccountService") //@Service(version = "1.0.0") public class EmployeeAccountServiceImpl implements EmployeeAccountService { @Autowired EmployeeRepository employeeRepository; ``` ``` <dubbo:service interface="com.xxx.service.employee.EmployeeAccountService" ref="employeeAccountService" version="1.0.0" validation="true"/> ```
Spring Boot启动报错,麻烦大神们看一下
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'appVersionServiceImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.likone.ofc.appVersion.repository.AppVersionRepository com.likone.ofc.appVersion.service.impl.AppVersionServiceImpl.appVersionRepository; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'appVersionRepository': Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.likone.spring.DefaultRepositoryFactoryBean]: No default constructor found; nested exception is java.lang.NoSuchMethodException: com.likone.spring.DefaultRepositoryFactoryBean.<init>() at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
Spring boot在非controller层使用@Autowired自动注入为null。(目录结构正确)
@Component class KafkaField { @Autowired @transient var streamingContext: StreamingContext = _ def fieldTop20(task: Task) = { val ssc = streamingContext val topicsSet = task.getTopic.split(",").toSet val kafkaParams = Map[String, Object]( ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG -> "192.100.1.30:9092", ConsumerConfig.GROUP_ID_CONFIG -> "1", ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG -> classOf[StringDeserializer], ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG -> classOf[StringDeserializer]) //创建流,模板代码,参数中的两个String代表的是Kafka中的键值对的数据,即key和value val messages = KafkaUtils.createDirectStream[String, String]( ssc, //本地策略 LocationStrategies.PreferConsistent, //消费者策略 //允许订阅固定的主题集合 ConsumerStrategies.Subscribe[String, String](topicsSet, kafkaParams)) //从kafka中将数据读出 // 获得这些行,将它们拆分为单词,数一数单词并打印出来 val lines = messages.map(_.value) val list = new util.ArrayList[String]() lines.foreachRDD(rdd => { val tops: Array[String] = rdd.take(20) for (i <- tops.indices) { println(tops(i)) // list.add(tops(i))+"\n" list.add(tops(i)) + "\t" } }) ssc.start() ssc.awaitTerminationOrTimeout(1000) ssc.stop() list } } ![图片说明](https://img-ask.csdn.net/upload/201902/20/1550651124_684747.png)
contorller中 中用注解调用ServiceImpl层异常,求前辈指点
我在contorller类中用注解的方式实现Service就会报错 ![图片说明](https://img-ask.csdn.net/upload/202001/16/1579141617_121594.png) 报错内容如下 org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private supermarket.service.UserServiceSuper supermarket.controller.UserController.userService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [supermarket.service.UserServiceSuper] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true), @org.springframework.beans.factory.annotation.Qualifier(value=userServiceMark)} <br/><br/> **但是我若是用context去取userService就正常运行,UserServiceSuper userService=(UserServiceSuper)context.getBean("userServiceMark");** 就是用注解就不行,我查了 网上说是@Autowired的错误,但我找不出来. 恳求前辈指点一下呀 感谢<BR/> 问题关键就是controller层无法通过注解调用 <br/><br/> ![图片说明](https://img-ask.csdn.net/upload/202001/16/1579141900_544612.png)<br/><br/> ![图片说明](https://img-ask.csdn.net/upload/202001/16/1579141908_230781.png)<br/><br/> ![图片说明](https://img-ask.csdn.net/upload/202001/16/1579141915_387319.png)<br/><br/> ![图片说明](https://img-ask.csdn.net/upload/202001/16/1579141921_582232.png)
spring boot 整合kafka报错怎么解决?
整合了一下spring boot跟kafka老是一直报错 ``` 2018-05-20 18:56:26.920 ERROR 4428 --- [ main] o.s.k.support.LoggingProducerListener : Exception thrown when sending a message with key='null' and payload='myTest--------1' to topic myTest: org.apache.kafka.common.errors.TimeoutException: Failed to update metadata after 60000 ms. ``` 请问一下各位大佬怎么解决的? 相应代码如下,也是参考了网上的: ``` <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.9.RELEASE</version> <dependency> <groupId>org.springframework.kafka</groupId> <artifactId>spring-kafka</artifactId> </dependency> <dependency> <groupId>org.apache.kafka</groupId> <artifactId>kafka-clients</artifactId> <version>0.10.2.0</version> </dependency> ``` kafka版本及配置 kafka_2.11-1.1.0 配置: ``` port = 9092 host.name = 阿里内网ip advertised.host.name = xxx.xxx.xx 阿里外网ip ``` 其他配置默认了 然后spring boot配置 ``` kafka: bootstrap-servers: xxx.xxx.xxx.xxx:9092 listener.concurrency: 3 producer.batch-size: 1000 consumer.group-id: test-consumer-group ``` ``` ``` @Configuration @EnableKafka public class KafkaConfiguration { } ``` @Component public class MsgProducer { private Logger log = LoggerFactory.getLogger(MsgProducer.class); @Autowired private KafkaTemplate<String, String> kafkaTemplate; public void sendMessage(String topicName, String jsonData) { log.info("向kafka推送数据:[{}]", jsonData); try { kafkaTemplate.send(topicName, jsonData); } catch (Exception e) { System.out.println("发送数据出错!!!"+topicName+","+jsonData); System.out.println("发送数据出错=====>"+e); log.error("发送数据出错!!!{}{}", topicName, jsonData); log.error("发送数据出错=====>", e); } //消息发送的监听器,用于回调返回信息 kafkaTemplate.setProducerListener(new ProducerListener<String, String>() { @Override public void onSuccess(String topic, Integer partition, String key, String value, RecordMetadata recordMetadata) { System.out.println("topic-----"+topic); } @Override public void onError(String topic, Integer partition, String key, String value, Exception exception) { } @Override public boolean isInterestedInSuccess() { log.info("数据发送完毕"); System.out.println("数据发送完毕"); return false; } }); } } @Component public class MsgConsumer { @KafkaListener(topics = {"myTest"}) public void processMessage(String content) { System.out.println("消息被消费"+content); } } @RunWith(SpringRunner.class) @SpringBootTest public class TestKafka { @Autowired private MsgProducer msgProducer; @Test public void test() throws Exception { msgProducer.sendMessage("myTest", "myTest--------1"); } } ``` 就是这样;运行test老是一直这个错误
Java学习的正确打开方式
在博主认为,对于入门级学习java的最佳学习方法莫过于视频+博客+书籍+总结,前三者博主将淋漓尽致地挥毫于这篇博客文章中,至于总结在于个人,实际上越到后面你会发现学习的最好方式就是阅读参考官方文档其次就是国内的书籍,博客次之,这又是一个层次了,这里暂时不提后面再谈。博主将为各位入门java保驾护航,各位只管冲鸭!!!上天是公平的,只要不辜负时间,时间自然不会辜负你。 何谓学习?博主所理解的学习,它是一个过程,是一个不断累积、不断沉淀、不断总结、善于传达自己的个人见解以及乐于分享的过程。
程序员必须掌握的核心算法有哪些?
由于我之前一直强调数据结构以及算法学习的重要性,所以就有一些读者经常问我,数据结构与算法应该要学习到哪个程度呢?,说实话,这个问题我不知道要怎么回答你,主要取决于你想学习到哪些程度,不过针对这个问题,我稍微总结一下我学过的算法知识点,以及我觉得值得学习的算法。这些算法与数据结构的学习大多数是零散的,并没有一本把他们全部覆盖的书籍。下面是我觉得值得学习的一些算法以及数据结构,当然,我也会整理一些看过...
有哪些让程序员受益终生的建议
从业五年多,辗转两个大厂,出过书,创过业,从技术小白成长为基层管理,联合几个业内大牛回答下这个问题,希望能帮到大家,记得帮我点赞哦。 敲黑板!!!读了这篇文章,你将知道如何才能进大厂,如何实现财务自由,如何在工作中游刃有余,这篇文章很长,但绝对是精品,记得帮我点赞哦!!!! 一腔肺腑之言,能看进去多少,就看你自己了!!! 目录: 在校生篇: 为什么要尽量进大厂? 如何选择语言及方...
大学四年自学走来,这些私藏的实用工具/学习网站我贡献出来了
大学四年,看课本是不可能一直看课本的了,对于学习,特别是自学,善于搜索网上的一些资源来辅助,还是非常有必要的,下面我就把这几年私藏的各种资源,网站贡献出来给你们。主要有:电子书搜索、实用工具、在线视频学习网站、非视频学习网站、软件下载、面试/求职必备网站。 注意:文中提到的所有资源,文末我都给你整理好了,你们只管拿去,如果觉得不错,转发、分享就是最大的支持了。 一、电子书搜索 对于大部分程序员...
linux系列之常用运维命令整理笔录
本博客记录工作中需要的linux运维命令,大学时候开始接触linux,会一些基本操作,可是都没有整理起来,加上是做开发,不做运维,有些命令忘记了,所以现在整理成博客,当然vi,文件操作等就不介绍了,慢慢积累一些其它拓展的命令,博客不定时更新 free -m 其中:m表示兆,也可以用g,注意都要小写 Men:表示物理内存统计 total:表示物理内存总数(total=used+free) use...
比特币原理详解
一、什么是比特币 比特币是一种电子货币,是一种基于密码学的货币,在2008年11月1日由中本聪发表比特币白皮书,文中提出了一种去中心化的电子记账系统,我们平时的电子现金是银行来记账,因为银行的背后是国家信用。去中心化电子记账系统是参与者共同记账。比特币可以防止主权危机、信用风险。其好处不多做赘述,这一层面介绍的文章很多,本文主要从更深层的技术原理角度进行介绍。 二、问题引入 假设现有4个人...
程序员接私活怎样防止做完了不给钱?
首先跟大家说明一点,我们做 IT 类的外包开发,是非标品开发,所以很有可能在开发过程中会有这样那样的需求修改,而这种需求修改很容易造成扯皮,进而影响到费用支付,甚至出现做完了项目收不到钱的情况。 那么,怎么保证自己的薪酬安全呢? 我们在开工前,一定要做好一些证据方面的准备(也就是“讨薪”的理论依据),这其中最重要的就是需求文档和验收标准。一定要让需求方提供这两个文档资料作为开发的基础。之后开发...
网页实现一个简单的音乐播放器(大佬别看。(⊙﹏⊙))
今天闲着无事,就想写点东西。然后听了下歌,就打算写个播放器。 于是乎用h5 audio的加上js简单的播放器完工了。 演示地点演示 html代码如下` music 这个年纪 七月的风 音乐 ` 然后就是css`*{ margin: 0; padding: 0; text-decoration: none; list-...
Python十大装B语法
Python 是一种代表简单思想的语言,其语法相对简单,很容易上手。不过,如果就此小视 Python 语法的精妙和深邃,那就大错特错了。本文精心筛选了最能展现 Python 语法之精妙的十个知识点,并附上详细的实例代码。如能在实战中融会贯通、灵活使用,必将使代码更为精炼、高效,同时也会极大提升代码B格,使之看上去更老练,读起来更优雅。
数据库优化 - SQL优化
以实际SQL入手,带你一步一步走上SQL优化之路!
2019年11月中国大陆编程语言排行榜
2019年11月2日,我统计了某招聘网站,获得有效程序员招聘数据9万条。针对招聘信息,提取编程语言关键字,并统计如下: 编程语言比例 rank pl_ percentage 1 java 33.62% 2 cpp 16.42% 3 c_sharp 12.82% 4 javascript 12.31% 5 python 7.93% 6 go 7.25% 7 p...
通俗易懂地给女朋友讲:线程池的内部原理
餐盘在灯光的照耀下格外晶莹洁白,女朋友拿起红酒杯轻轻地抿了一小口,对我说:“经常听你说线程池,到底线程池到底是个什么原理?”
《奇巧淫技》系列-python!!每天早上八点自动发送天气预报邮件到QQ邮箱
将代码部署服务器,每日早上定时获取到天气数据,并发送到邮箱。 也可以说是一个小型人工智障。 知识可以运用在不同地方,不一定非是天气预报。
经典算法(5)杨辉三角
杨辉三角 是经典算法,这篇博客对它的算法思想进行了讲解,并有完整的代码实现。
英特尔不为人知的 B 面
从 PC 时代至今,众人只知在 CPU、GPU、XPU、制程、工艺等战场中,英特尔在与同行硬件芯片制造商们的竞争中杀出重围,且在不断的成长进化中,成为全球知名的半导体公司。殊不知,在「刚硬」的背后,英特尔「柔性」的软件早已经做到了全方位的支持与支撑,并持续发挥独特的生态价值,推动产业合作共赢。 而对于这一不知人知的 B 面,很多人将其称之为英特尔隐形的翅膀,虽低调,但是影响力却不容小觑。 那么,在...
腾讯算法面试题:64匹马8个跑道需要多少轮才能选出最快的四匹?
昨天,有网友私信我,说去阿里面试,彻底的被打击到了。问了为什么网上大量使用ThreadLocal的源码都会加上private static?他被难住了,因为他从来都没有考虑过这个问题。无独有偶,今天笔者又发现有网友吐槽了一道腾讯的面试题,我们一起来看看。 腾讯算法面试题:64匹马8个跑道需要多少轮才能选出最快的四匹? 在互联网职场论坛,一名程序员发帖求助到。二面腾讯,其中一个算法题:64匹...
面试官:你连RESTful都不知道我怎么敢要你?
干货,2019 RESTful最贱实践
为啥国人偏爱Mybatis,而老外喜欢Hibernate/JPA呢?
关于SQL和ORM的争论,永远都不会终止,我也一直在思考这个问题。昨天又跟群里的小伙伴进行了一番讨论,感触还是有一些,于是就有了今天这篇文。 声明:本文不会下关于Mybatis和JPA两个持久层框架哪个更好这样的结论。只是摆事实,讲道理,所以,请各位看官勿喷。 一、事件起因 关于Mybatis和JPA孰优孰劣的问题,争论已经很多年了。一直也没有结论,毕竟每个人的喜好和习惯是大不相同的。我也看...
白话阿里巴巴Java开发手册高级篇
不久前,阿里巴巴发布了《阿里巴巴Java开发手册》,总结了阿里巴巴内部实际项目开发过程中开发人员应该遵守的研发流程规范,这些流程规范在一定程度上能够保证最终的项目交付质量,通过在时间中总结模式,并推广给广大开发人员,来避免研发人员在实践中容易犯的错误,确保最终在大规模协作的项目中达成既定目标。 无独有偶,笔者去年在公司里负责升级和制定研发流程、设计模板、设计标准、代码标准等规范,并在实际工作中进行...
SQL-小白最佳入门sql查询一
不要偷偷的查询我的个人资料,即使你再喜欢我,也不要这样,真的不好;
redis分布式锁,面试官请随便问,我都会
文章有点长并且绕,先来个图片缓冲下! 前言 现在的业务场景越来越复杂,使用的架构也就越来越复杂,分布式、高并发已经是业务要求的常态。像腾讯系的不少服务,还有CDN优化、异地多备份等处理。 说到分布式,就必然涉及到分布式锁的概念,如何保证不同机器不同线程的分布式锁同步呢? 实现要点 互斥性,同一时刻,智能有一个客户端持有锁。 防止死锁发生,如果持有锁的客户端崩溃没有主动释放锁,也要保证锁可以正常释...
项目中的if else太多了,该怎么重构?
介绍 最近跟着公司的大佬开发了一款IM系统,类似QQ和微信哈,就是聊天软件。我们有一部分业务逻辑是这样的 if (msgType = "文本") { // dosomething } else if(msgType = "图片") { // doshomething } else if(msgType = "视频") { // doshomething } else { // doshom...
Nginx 原理和架构
Nginx 是一个免费的,开源的,高性能的 HTTP 服务器和反向代理,以及 IMAP / POP3 代理服务器。Nginx 以其高性能,稳定性,丰富的功能,简单的配置和低资源消耗而闻名。 Nginx 的整体架构 Nginx 里有一个 master 进程和多个 worker 进程。master 进程并不处理网络请求,主要负责调度工作进程:加载配置、启动工作进程及非停升级。worker 进程负责处...
Python 编程开发 实用经验和技巧
Python是一门很灵活的语言,也有很多实用的方法,有时候实现一个功能可以用多种方法实现,我这里总结了一些常用的方法和技巧,包括小数保留指定位小数、判断变量的数据类型、类方法@classmethod、制表符中文对齐、遍历字典、datetime.timedelta的使用等,会持续更新......
YouTube排名第一的励志英文演讲《Dream(梦想)》
Idon’t know what that dream is that you have, I don't care how disappointing it might have been as you've been working toward that dream,but that dream that you’re holding in your mind, that it’s po...
“狗屁不通文章生成器”登顶GitHub热榜,分分钟写出万字形式主义大作
一、垃圾文字生成器介绍 最近在浏览GitHub的时候,发现了这样一个骨骼清奇的雷人项目,而且热度还特别高。 项目中文名:狗屁不通文章生成器 项目英文名:BullshitGenerator 根据作者的介绍,他是偶尔需要一些中文文字用于GUI开发时测试文本渲染,因此开发了这个废话生成器。但由于生成的废话实在是太过富于哲理,所以最近已经被小伙伴们给玩坏了。 他的文风可能是这样的: 你发现,...
程序员:我终于知道post和get的区别
是一个老生常谈的话题,然而随着不断的学习,对于以前的认识有很多误区,所以还是需要不断地总结的,学而时习之,不亦说乎
《程序人生》系列-这个程序员只用了20行代码就拿了冠军
你知道的越多,你不知道的越多 点赞再看,养成习惯GitHub上已经开源https://github.com/JavaFamily,有一线大厂面试点脑图,欢迎Star和完善 前言 这一期不算《吊打面试官》系列的,所有没前言我直接开始。 絮叨 本来应该是没有这期的,看过我上期的小伙伴应该是知道的嘛,双十一比较忙嘛,要值班又要去帮忙拍摄年会的视频素材,还得搞个程序员一天的Vlog,还要写BU...
加快推动区块链技术和产业创新发展,2019可信区块链峰会在京召开
11月8日,由中国信息通信研究院、中国通信标准化协会、中国互联网协会、可信区块链推进计划联合主办,科技行者协办的2019可信区块链峰会将在北京悠唐皇冠假日酒店开幕。   区块链技术被认为是继蒸汽机、电力、互联网之后,下一代颠覆性的核心技术。如果说蒸汽机释放了人类的生产力,电力解决了人类基本的生活需求,互联网彻底改变了信息传递的方式,区块链作为构造信任的技术有重要的价值。   1...
Java世界最常用的工具类库
Apache Commons Apache Commons有很多子项目 Google Guava 参考博客
相关热词 基于c#波形控件 c# 十进制转十六进制 对文件aes加密vc# c#读取栈中所有的值 c# rsa256加密 好 学c# 还是c++ c# 和java的差距 c# curl网络框架 c# https证书请求 c# 中崎
立即提问