Java UnsatisfiedDependencyException:创建名为“userController”的 bean 时出错:依赖项不满足

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45482773/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 02:03:01  来源:igfitidea点击:

UnsatisfiedDependencyException: Error creating bean with name 'userController': Unsatisfied dependency

javaspringspring-mvc

提问by Umapathi

I'm new to spring MVC. I'm facing UnsatisfiedDependencyException. I have added stereotype annotationsbut still I'm facing same issue.

我是 Spring MVC 的新手。我面对UnsatisfiedDependencyException. 我已经添加,stereotype annotations但我仍然面临同样的问题。

Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userController': Unsatisfied dependency expressed through field 'userService'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean found for dependency [com.demo.app.service.UserService]: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} looking positive replay.

上下文初始化期间遇到异常 - 取消刷新尝试:org.springframework.beans.factory.UnsatisfiedDependencyException:创建名为“userController”的 bean 时出错:通过字段“userService”表达的不满意依赖;嵌套异常是 org.springframework.beans.factory.NoSuchBeanDefinitionException: Noqualifying bean found for dependency [com.demo.app.service.UserService]: 预计至少有 1 个 bean 有资格作为自动装配候选。依赖注释:{@org.springframework.beans.factory.annotation.Autowired(required=true)} 看起来很积极。

UserController:

用户控制器:

@CrossOrigin
@RestController
public class UserController {

@Autowired(required=true)
private UserService userService;

@RequestMapping(value = { "/userSave" },consumes = {"multipart/form-data"}, method = RequestMethod.POST)
@ResponseBody
public String saveUserDetails(@RequestPart(value="file",required=false) MultipartFile file,
        @RequestPart("user")User user,
        HttpSession session, HttpServletRequest request,
        HttpServletResponse response){
        System.out.println("data reached...!");
        String result=userService.saveUserData(user,session);
        return result;

}

}

}

UserService:

用户服务:

public interface UserService {
     public String saveUserData(User user,HttpSession session);
}

UserServiceImpl:

UserServiceImpl:

@Service("userService")
public class UserServiceImpl implements UserService{

@Autowired
UserRepository userRepository;

public String saveUserData(User user,HttpSession session){
    String  output;
    Date regDate=new Date();
    user.setRegDate(regDate);
    output= userRepository.saveUserData(user);
    return output;
}

}

}

UserRepository:

用户库:

@Component
@Transactional
public class UserRepository  extends BaseRepository{

@Autowired
protected SessionFactory sessionFactory;


public String saveUserData(User user) {

    final Session session = (Session) getSessionFactory();
    try {
        session.beginTransaction();
        Query query=session.createQuery("UPDATE User set user_Name =:userName,"
                + "reg_Date =:regDate,img_Id=:imgId");
        query.setParameter("userName", user.getUserName());
        query.setParameter("regDate", user.getRegDate());
        query.setParameter("imgId", user.getImgId());
        query.setParameter("emailId", user.getImgId());
        session.save(user);
        session.getTransaction().commit();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

}

}

spring.xml:

弹簧.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"
    xmlns:util="http://www.springframework.org/schema/util" xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
                    http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
                    http://www.springframework.org/schema/context 
                    http://www.springframework.org/schema/context/spring-context-4.0.xsd
                    http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
                    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
                    ">

    <context:annotation-config />

    <context:component-scan base-package="com.demo.app" />
    <mvc:default-servlet-handler />

    <mvc:annotation-driven>
        <mvc:message-converters register-defaults="true">
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <property name="supportedMediaTypes" value="text/plain;charset=UTF-8" />
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

    <bean id="jspViewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass"
            value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/html/" />
        <property name="suffix" value="html" />
    </bean>

    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/UserDB" />
        <property name="username" value="root" />
        <property name="password" value="password" />
    </bean>

    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="annotatedClasses">
            <list>
                <value>com.demo.app.model.User</value>

            </list>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
            </props>
        </property>
    </bean>

    <tx:annotation-driven transaction-manager="transactionManager" />
    <bean id="transactionManager"
        class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>
    <bean
        class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
        <property name="exceptionMappings">
            <props>
                <prop key="java.lang.Exception">Error</prop>
            </props>
        </property>
    </bean>
    <bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="2097152" />
    </bean>
</beans>

Error:

错误:

SEVERE: Context initialization failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userController': Unsatisfied dependency expressed through field 'userService'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean found for dependency [com.demo.app.service.UserService]: 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:569)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:349)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1219)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getObject(AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:751)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:861)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:541)
    at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:668)

Please help me,

请帮我,

Thank you

谢谢

采纳答案by Umapathi

Finally i resolved .spring dependency jar file versions are mismatched. all spring dependency versions are same.

最后我解决了 .spring 依赖 jar 文件版本不匹配的问题。所有 spring 依赖版本都相同。

     <dependencies>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>4.2.3.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-config</artifactId>
    <version>4.2.3.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-aop</artifactId>
    <version>4.2.3.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-config</artifactId>
    <version>4.2.3.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-tx</artifactId>
    <version>4.2.3.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>4.2.3.RELEASE</version>
</dependency>
 <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-orm</artifactId>
   <version>4.2.3.RELEASE</version>
</dependency>
  </dependencies>

回答by Vitalii Muzalevskyi

@Service("userService")should be near implementation not interface.

@Service("userService")应该接近实现而不是接口。

回答by Ravikumar Rathod

@service annotation use in service implementation, not in interface because interface is only mapping controller to actual service implementation and other logic only...

@service 注释在服务实现中使用,而不是在接口中使用,因为接口只是将控制器映射到实际的服务实现和其他逻辑......

回答by Sam

"No qualifying bean found for dependency [com.demo.app.service.UserService]: expected at least 1 bean which qualifies as autowire candidate."

“没有找到依赖 [com.demo.app.service.UserService] 的合格 bean:预计至少有 1 个 bean 有资格作为自动装配候选。”

Above error means UserService bean were not created. Can you please check whether you've give the correct base package here.

以上错误表示未创建 UserService bean。你能在这里检查一下你是否提供了正确的基础包。

Also can you please change annotation to UserRepository @Component to @Repository.

您也可以将注释更改为 UserRepository @Component 为 @Repository。

回答by parsecer

My problem was that I didn't have @EnableWebSecurityin this class:

我的问题是我@EnableWebSecurity在这门课上没有:

@Configuration
@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        // add our users for in memory authentication

        User.UserBuilder users = User.withDefaultPasswordEncoder();

        auth.inMemoryAuthentication()
                .withUser(users.username("john").password("test123").roles("EMPLOYEE"))
                .withUser(users.username("mary").password("test123").roles("MANAGER"))
                .withUser(users.username("susan").password("test123").roles("ADMIN"));
    }



    @Override
    protected void configure(HttpSecurity http)  throws Exception {
        http.authorizeRequests().anyRequest().authenticated().and()
                .formLogin().loginPage("/showLoginPage")
                .loginProcessingUrl("/authenticateTheUser")
                .permitAll();
    }
}

回答by Samba Namuduri

I too had this issue.

我也有这个问题。

In my case I thought it was the Maven dependencies and updated them and got all my Java files as error.

在我的情况下,我认为这是 Maven 依赖项并更新了它们并将我的所有 Java 文件作为错误。

Finally, after updating all the Maven dependencies and added this

最后,在更新了所有 Maven 依赖项并添加了这个之后

<dependency>
  <groupId>org.glassfish.jaxb</groupId>
  <artifactId>jaxb-runtime</artifactId>
  <version>2.3.1</version>
</dependency>

That works for projects which are Java versions > 9 I was using OpenJDK 11 in my project. Thanks. Hope it helps.

这适用于 Java 版本 > 9 我在我的项目中使用 OpenJDK 11 的项目。谢谢。希望能帮助到你。

Happy Coding.

快乐编码。