UnsatisfiedDependencyException:创建名为'userController'的bean时出错:不满意的依赖项

时间:2017-08-03 11:23:22

标签: java spring spring-mvc

我是初学MVC的新手。我正面对UnsatisfiedDependencyException。我添加了stereotype annotations,但我仍面临同样的问题。

  

在上下文初始化期间遇到异常 - 取消   刷新尝试:   org.springframework.beans.factory.UnsatisfiedDependencyException:   创建名为'userController'的bean时出错:不满意的依赖项   通过字段'userService'表示;嵌套异常是   org.springframework.beans.factory.NoSuchBeanDefinitionException:没有   发现依赖的限定bean   [com.demo.app.service.UserService]:预计至少有1个bean   有资格成为autowire候选人。依赖注释:   {@ org.springframework.beans.factory.annotation.Autowired(所需=真)}   看起来积极的重播。

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:

@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 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>

错误:

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$1.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)

请帮助我,

谢谢

7 个答案:

答案 0 :(得分:3)

<div class="parent"> <h4>Parent 1</h4> <div class="items"> <span>i1</span> <span>i2</span> <span>i3</span> <span>i4</span> <span>i5</span> </div> </div> <div class="parent"> <h4>Parent 2</h4> <div class="items"> <span>i1</span> <span>i2</span> <span>i3</span> <span>i4</span> <span>i5</span> </div> </div> <div class="parent"> <h4>Parent 3</h4> <div class="items"> <span>i1</span> <span>i2</span> <span>i3</span> <span>i4</span> <span>i5</span> </div> </div> <div class="parent"> <h4>Parent 4</h4> <div class="items"> <span>i1</span> <span>i2</span> <span>i3</span> <span>i4</span> <span>i5</span> </div> </div> <div class="parent"> <h4>Parent 5</h4> <div class="items"> <span>i1</span> <span>i2</span> <span>i3</span> <span>i4</span> <span>i5</span> </div> </div>应该接近实现而不是接口。

答案 1 :(得分:1)

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

答案 2 :(得分:1)

最后我解决了.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>

答案 3 :(得分:1)

检查以下所有要点:

1 - @Entity 添加到所有实体。

2 - @Service 添加到所有 DAO 或任何其他组件中。

3 - @RestController 添加到所有控制器。

我的错误没有在我的实体上添加 @Entity

答案 4 :(得分:0)

&#34;找不到依赖项[com.demo.app.service.UserService]的限定bean:预计至少有1个bean可以作为autowire候选者。&#34;

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

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

答案 5 :(得分:0)

我的问题是我没有@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();
    }
}

答案 6 :(得分:0)

我也有这个问题。

在我的情况下,我认为这是Maven依赖关系,并对其进行了更新,并将我的所有Java文件都作为错误。

最后,在更新所有Maven依赖项并添加后

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

适用于Java版本> 9的项目 我在项目中使用的是OpenJDK 11。 谢谢。希望对您有所帮助。

快乐编码。 ??

相关问题