【问题标题】:Could not autowire field/expected at least 1 bean which qualifies as autowire candidate无法自动装配字段/预计至少有 1 个符合自动装配候选资格的 bean
【发布时间】:2016-04-08 11:00:12
【问题描述】:

我对 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,尽管它已定义。请帮帮我!

【问题讨论】:

    标签: spring javabeans autowired


    【解决方案1】:

    几件事:

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

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

    3. 您确定您的包仅命名为controllerdao 等而不是xxx.yyy.controller?因为如果他们有前缀,你的扫描在这里是不正确的:

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

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

      <context:component-scan base-package="service, dao, controller, ..." />
      

    【讨论】:

    • 1.我试过了,结果一样,2.我试过了,结果一样,3.我敢肯定,他们在src,但还是谢谢你
    【解决方案2】:

    要调试,暂时注释:

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

    并在你的控制器中打印所有由 spring 容器加载的 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 已加载。

    【讨论】:

    • 应用程序由于 spring 配置而无法启动,所以我无论如何都看不到它们
    猜你喜欢
    • 2020-02-12
    • 2021-02-20
    • 2017-10-24
    • 2021-10-12
    • 1970-01-01
    • 1970-01-01
    • 2021-01-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多