无法自动装配字段/预期至少1个符合autowire候选资格的bean

时间:2016-04-08 11:00:12

标签: spring javabeans autowired

我对Spring很陌生,虽然之前我已经将它用于了几个项目,并且我看到了很多类似的问题,但我无法弄清楚这个例外有什么问题:

SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener    org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'applicationController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: public service.UserServiceI controller.ApplicationController.userService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [service.UserServiceI] 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=userService)}

这是堆栈跟踪的相关部分。

这是我的控制器类:

@Controller
@RequestMapping("/")
public class ApplicationController {

@Autowired 
@Qualifier("userService")
public UserServiceI userService;
}

这是我的UserService界面:

public interface UserService {
   //methods
}

实施:

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

@Autowired
private UserDao dao;

//methods
}

这是我的XML配置文件:

<context:component-scan base-package="configuration">
</context:component-scan>


<bean id="resView" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
    <property name="prefix" value="/WEB-INF/" />
    <property name="suffix" value=".jsp" />
</bean>
<mvc:default-servlet-handler/>
<mvc:resources location="/resources/css/" mapping="/resources/css/*">
</mvc:resources>
<mvc:resources location="/resources/js/" mapping="/resources/js/*">
</mvc:resources>
<context:annotation-config></context:annotation-config>
<mvc:annotation-driven></mvc:annotation-driven>
<mvc:default-servlet-handler />
<context:component-scan base-package="controller">
</context:component-scan>

<context:component-scan base-package="dao"></context:component-scan>
<context:component-scan base-package="model"></context:component-scan>
<context:component-scan base-package="service"
    use-default-filters="true">
</context:component-scan>

这是Spring配置:

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "{configuration, controller, dao, model,    service}")
public class SpringConfig extends WebMvcConfigurerAdapter{

@Override
public void configureViewResolvers(ViewResolverRegistry registry) {
     InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
     viewResolver.setViewClass(JstlView.class);
     viewResolver.setPrefix("/WebContent/");
     viewResolver.setSuffix(".jsp");
     registry.viewResolver(viewResolver);
}

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}

}

和Hibernate配置:

@Configuration
@EnableTransactionManagement
@ComponentScan({"configuration", "controller", "dao", "model", "service"})
@PropertySource(value = {"classpath:appProperties"})
public class HibernateConfig {

@Autowired
private Environment environment;

@Bean
public LocalSessionFactoryBean sessionFactory(){
    LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
    sessionFactory.setDataSource(dataSource());
    sessionFactory.setPackagesToScan(new String[] {"model"});
    sessionFactory.setHibernateProperties(hibernateProperties());
    return sessionFactory;
}

@Bean
public DataSource dataSource(){
    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setDriverClassName(environment.getRequiredProperty("jdbc.driverClassName"));
    dataSource.setUrl(environment.getRequiredProperty("jdbc.url"));
    dataSource.setUsername(environment.getRequiredProperty("jdbc.username"));
    dataSource.setPassword(environment.getRequiredProperty("jdbc.password"));
    return dataSource;
}

@Bean
public Properties hibernateProperties(){
    Properties hibernateProperties = new Properties();
    hibernateProperties.put("hibernate.dialect",environment.getRequiredProperty("hibernate.dialect"));
    hibernateProperties.put("hibernate.show_sql", environment.getRequiredProperty("hibernate.show_sql"));
    hibernateProperties.put("hibernate.format_sql", environment.getRequiredProperty("hibernate.format_sql"));
    return hibernateProperties;
}

@Bean
@Autowired
public HibernateTransactionManager transactionManager(SessionFactory s) {
    HibernateTransactionManager txManager = new HibernateTransactionManager();
    txManager.setSessionFactory(s);
    return txManager;
}
}

和pom.xml

<dependencies>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>4.2.0.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-tx</artifactId>
    <version>4.2.0.RELEASE</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.2.3</version>
</dependency>
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.1.0</version>
</dependency>
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>4.2.0.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
    <version>4.2.0.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-core</artifactId>
    <version>4.2.0.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-beans</artifactId>
    <version>4.2.0.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-orm</artifactId>
    <version>4.2.0.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core</artifactId>
    <version>4.3.6.Final</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.31</version>
</dependency>
<dependency>
    <groupId>javax.servlet.jsp</groupId>
    <artifactId>jsp-api</artifactId>
    <version>2.2</version>
</dependency>

我评论了Controller中的代码,结果是它无法自动装配SessionFactory,尽管已定义。请帮帮我!

2 个答案:

答案 0 :(得分:0)

少数事情:

1-你应该自动装配接口,而不是实现:

 <div class="row">
    <div class="col-xs-12 col-sm-12 col-md-12">
            <button class="btn btn-primary  btn-block col-md-12  ">Filtrera</button>
        </div>
    </div>

2-删除传递给@Autowired public UserService userService; @Service的值参数,除非你想使用一些花哨的名字,否则Spring会自动在小写中使用bean的名字(记住你应该自动装配接口);

3-您确定您的软件包仅被命名为UserServiceIcontroller等,而不是dao吗?因为如果他们有预加,那么您的扫描不正确:

xxx.yyy.controller

3.1-只是一个提示,但您可以使用逗号分隔您的包,而不是多个声明:

<context:component-scan base-package="service"
    use-default-filters="true">
</context:component-scan>

答案 1 :(得分:-1)

要调试,暂时评论:

@Autowired 
@Qualifier("userService")
public UserServiceI userService;

并打印控制器中弹簧容器加载的所有bean:

@Autowired
private ApplicationContext applicationContext;

@RequestMapping("/print")
public void print() {
    String[] beanNames = applicationContext.getBeanDefinitionNames();
    for (String beanName : beanNames) {
        System.out.println(beanName + " : " + applicationContext.getBean(beanName).getClass().toString());
    }
}

并确保加载了服务bean。