Reasons and solutions for failure to use annotations

Error when starting the project:

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userController': Unsatisfied dependency expressed through field 'userSer'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean found for dependency [com.hans.service.UserService]: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

There are generally two situations when this error occurs.

The first is that the implementation class of the Service interface does not add the @Service("xxx") annotation, which is easy to solve, and it will be finished if it is not added.

The second is the scanning problem of the package in the configuration file, which is also very simple, find the relevant configuration in the configuration file.

The first modification

    Configured in the relevant configuration of spring-mybatis

<!-- Auto Scan -->  
    <context:component-scan base-package="com.hans"/>  
The value in base-package here can be com.hans or com.hans.*, the effect is the same.

The second modification

    Configure in springmvc related configuration files

before modification

<!-- Automatically scan the package, so that SpringMVC thinks that the class annotated with @controller under the package is a controller (registering components marked with annotations such as @Component, @Controller, @Service, @Repository, etc.)-->  
    <context:component-scan base-package="com.hans.controller" />  

after modification

    <!-- Automatically scan the package, so that SpringMVC thinks that the class annotated with @controller under the package is a controller (registering components marked with annotations such as @Component, @Controller, @Service, @Repository, etc.)-->  
    <context:component-scan base-package="com.hans.controller,com.hans.entity,com.hans.service" />  

Speaking of this, let’s talk about it every day. Some projects are still using new objects. The problems that can be solved with configuration are the best. It’s a waste of time to have no tools.

The solution is as above, add the package of entity to automatically scan, add @Component("xxx") to the entity class, and @Autowired can be used when it is used, which is simple and convenient.

Personally, I feel that the way of new object is to cut off one's arm. Spring's ioc is done for nothing, although our company's project is played like this, hahaha, embarrassing, the project is too big, no one will do it, let's use it first, left hand A new object, a new object in the right hand, sour.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326440522&siteId=291194637