【问题标题】:No Qualifying Bean of Type in Pure Java Spring Servlet Configuration纯 Java Spring Servlet 配置中没有限定类型的 Bean
【发布时间】:2015-09-12 13:50:08
【问题描述】:

我正在尝试使用 servlets 3 在纯 java 中构建一个小型 Spring 应用程序,但我的 @Autowired 注释有问题:

这是堆栈跟踪:

[main] INFO org.springframework.web.servlet.DispatcherServlet - FrameworkServlet 'dispatcher': initialization started
[main] INFO org.springframework.web.context.support.AnnotationConfigWebApplicationContext - Refreshing WebApplicationContext for namespace 'dispatcher-servlet': startup date [Thu Jun 25 21:33:25 BST 2015]; root of context hierarchy
[main] INFO org.springframework.web.context.support.AnnotationConfigWebApplicationContext - Registering annotated classes: [class com.foo.shop.ServletContext]
[main] WARN org.springframework.web.context.support.AnnotationConfigWebApplicationContext - Exception encountered during context initialization - cancelling refresh attempt
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'productController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.foo.shop.database.dao.ProductDao com.foo.shop.webapp.controller.ProductController.productDao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.foo.shop.database.dao.ProductDao] 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)}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1210)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:755)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
    at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:663)
    at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:535)
    at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:489)
    at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
    at javax.servlet.GenericServlet.init(GenericServlet.java:242)
    at org.eclipse.jetty.servlet.ServletHolder.initServlet(ServletHolder.java:492)
    at org.eclipse.jetty.servlet.ServletHolder.doStart(ServletHolder.java:312)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:59)
    at org.eclipse.jetty.servlet.ServletHandler.initialize(ServletHandler.java:777)
    at org.eclipse.jetty.servlet.ServletHandler.updateMappings(ServletHandler.java:1227)
    at org.eclipse.jetty.servlet.ServletHandler.setServletMappings(ServletHandler.java:1286)
    at org.eclipse.jetty.servlet.ServletHandler.addServletMapping(ServletHandler.java:886)
    at org.eclipse.jetty.servlet.ServletHolder$Registration.addMapping(ServletHolder.java:657)
    at org.springframework.web.servlet.support.AbstractDispatcherServletInitializer.registerDispatcherServlet(AbstractDispatcherServletInitializer.java:97)
    at org.springframework.web.servlet.support.AbstractDispatcherServletInitializer.onStartup(AbstractDispatcherServletInitializer.java:68)
    at org.springframework.web.SpringServletContainerInitializer.onStartup(SpringServletContainerInitializer.java:175)
    at org.eclipse.jetty.plus.annotation.ContainerInitializer.callStartup(ContainerInitializer.java:100)
    at org.eclipse.jetty.annotations.ServletContainerInitializerListener.contextInitialized(ServletContainerInitializerListener.java:99)
    at org.eclipse.jetty.server.handler.ContextHandler.callContextInitialized(ContextHandler.java:764)
    at org.eclipse.jetty.servlet.ServletContextHandler.callContextInitialized(ServletContextHandler.java:406)
    at org.eclipse.jetty.server.handler.ContextHandler.startContext(ContextHandler.java:756)
    at org.eclipse.jetty.servlet.ServletContextHandler.startContext(ServletContextHandler.java:242)
    at org.eclipse.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1221)
    at org.eclipse.jetty.server.handler.ContextHandler.doStart(ContextHandler.java:699)
    at org.eclipse.jetty.webapp.WebAppContext.doStart(WebAppContext.java:454)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:59)
    at org.eclipse.jetty.server.handler.HandlerWrapper.doStart(HandlerWrapper.java:90)
    at org.eclipse.jetty.server.Server.doStart(Server.java:263)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:59)
    at runjettyrun.Bootstrap.main(Bootstrap.java:80)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.foo.shop.database.dao.ProductDao com.foo.shop.webapp.controller.ProductController.productDao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.foo.shop.database.dao.ProductDao] 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)}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:561)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
    ... 40 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.foo.shop.database.dao.ProductDao] 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)}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1301)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1047)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:942)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:533)
    ... 42 more

这是我的初始化程序:

package com.foo.shop;

public class ApplicationInitialiser extends AbstractDispatcherServletInitializer implements WebApplicationInitializer {

  @Override
  protected WebApplicationContext createRootApplicationContext() {
    AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext();
    applicationContext.register(ApplicationContext.class);
    return applicationContext;
  }

  @Override
  protected WebApplicationContext createServletApplicationContext() {
    AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext();
    applicationContext.register(ServletContext.class);
    return applicationContext;
  }

  @Override
  protected String[] getServletMappings() {
    return new String[] { "/*" };
  }
}

这是应用程序上下文:

package com.foo.shop;

import com.foo.shop.database.dao.ProductDao;
import com.foo.shop.database.jpa.JpaProductDao;

@Configuration
@ComponentScan(basePackages = {"com.foo.shop.database.jpa"})
public class ApplicationContext {

  public static final String PERSISTENCE_UNIT = "com.foo.shop.database";

  @Bean
  public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
      LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
      return entityManagerFactoryBean;
  }

  @Bean
  public JpaTransactionManager JpaTransactionManager() {
      JpaTransactionManager jpaTransactionManager = new JpaTransactionManager();
      return jpaTransactionManager;
  }

  @Bean 
  ProductDao getProductDao() {
    return new JpaProductDao();
  }
}

servlet 上下文:

package com.foo.shop;

@Configuration
@EnableWebMvc
@ComponentScan({
  "com.foo.shop.webapp.controller",
  "com.foo.shop.webapp.rest"})
public class ServletContext extends WebMvcConfigurerAdapter {

  @Override
  public void configureViewResolvers(ViewResolverRegistry registry) {
    InternalResourceViewResolver jspResolver = new InternalResourceViewResolver();
    jspResolver.setViewClass(JstlView.class);
    registry.viewResolver(jspResolver);
  }

  @Override
  public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/static/**").addResourceLocations("/WEB-INF/static/");
    registry.addResourceHandler("/template/**").addResourceLocations("WEB-INF/static/template/");
    registry.addResourceHandler("/css/**").addResourceLocations("/WEB-INF/css/");
    registry.addResourceHandler("js/**").addResourceLocations("WEB-INF/js/vendor/");
  }
}

GenericDao 接口:

package com.foo.shop.database;

import java.io.Serializable;
import java.util.List;

public interface GenericDao<T, PK extends Serializable> {

  public T getById(PK id);

  public List<T> getAll();

  public void update(T entity);

  public void save(T entity);

  public void delete(T entity);
}

GenericDao 实现

package com.foo.shop.database;

public abstract class GenericDaoImpl<T, PK extends Serializable> implements GenericDao<T, PK> {

@PersistenceContext(unitName = "com.foo.shop.database")
private EntityManager entityManager;

private Class<T> entityType;


public GenericDaoImpl(Class<T> entityType) {
  this.entityType = entityType;
}

@Override
public T getById(PK id) {
  return entityManager.find(entityType, id);
}

@Override
public List<T> getAll() {
  entityManager.getCriteriaBuilder().createQuery(entityType);
  CriteriaQuery<T> cq = entityManager.getCriteriaBuilder().createQuery(entityType);
  Root<T> product = cq.from(entityType);
  cq.select(product);
  TypedQuery<T> q = entityManager.createQuery(cq);
  return q.getResultList();
}

@Override
public void save(T entity) {
  this.entityManager.persist(entity);
}

@Override
public void update(T entity) {
  this.entityManager.merge(entity);
}

@Override
public void delete(T entity) {
  this.entityManager.remove(entity);
  }
}

ProductDao 接口

package com.foo.shop.database.dao;

import com.foo.shop.database.GenericDao;
import com.foo.shop.domain.Product;

public interface ProductDao extends GenericDao<Product, Long>{
}

产品DAO的实现。

package com.foo.shop.database.jpa;

@Repository("productDao")
public class JpaProductDao extends GenericDaoImpl<Product, Long> implements ProductDao {

  @PersistenceContext(unitName="com.foo.shop.database")
  private EntityManager entityManager;

  public JpaProductDao() {
    super(Product.class);
  }

}

最后,尝试实例化的组件类:

package com.foo.shop.webapp.controller;

import com.foo.shop.database.dao.ProductDao;

@Controller
public class ProductController {

  @Autowired
  private ProductDao productDao;

  @RequestMapping(value = { "/product" }, method = RequestMethod.GET)
  public ModelAndView productPage(
      @RequestParam(value = "name", defaultValue = "Guy") String name) {

      // Model and view stuff
  }
}

我不知道我在这里搞砸了什么,但我知道这与 DAO bean 位于根上下文中有关,而 servlet 只是在照顾自己。对此的任何帮助表示赞赏,因为我能够找到的所有配置主要与基于 xml 的配置有关。

谢谢,

【问题讨论】:

  • 异常的完整堆栈跟踪是?
  • 看起来很奇怪。错误消息查找具有不同包com.codeshaw.shop.database.dao.ProductDao 的类。而实际的包是com.foo.shop.database.dao.ProductDao
  • 给我们看看ProductDao和JpaProductDao的代码。
  • 随通用 dao 实现一起更新。

标签: java spring spring-mvc servlets


【解决方案1】:

不是 100% 确定这会导致您的问题,但是...

Spring 参考 documentation 说,当使用 Java 配置时,您扩展 AbstractAnnotationConfigDispatcherServletInitializer 以初始化您的 Spring 应用程序上下文,并且您应该覆盖 getRootConfigClasses()getServletConfigClasses() 方法。

AbstractDispatcherServletInitializer 类、createRootApplicationContext()createServletApplicationContext() 方法用于 XML 配置。

所以你的初始化器应该是这样的:

public class ApplicationInitialiser extends AbstractAnnotationConfigDispatcherServletInitializer { //No need to also implement WebApplicationInitializer here


    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class[]{ApplicationContext.class};
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class[] { ServletContext.class };
    }

    @Override
    protected String[] getServletMappings() {
        return new String[] { "/*" };
    }
}

另一个与您的代码无关(可能会也可能不会导致问题)...

您正在组件扫描您的 JPA 包:

@Configuration
@ComponentScan(basePackages = {"com.foo.shop.database.jpa"})
public class ApplicationContext {
    ...
}

而且你也在手动构建 bean:

@Bean 
ProductDao getProductDao() {
    return new JpaProductDao();
}

你只需要做一个或另一个,而不是两个。

【讨论】:

  • AbstractAnnotationConfigDispatcherServletInitializer的实现这可能不会导致你的问题......嗯
【解决方案2】:

您正在创建 JpaProductDao 的两个实例

第一:

package com.foo.shop.database.jpa;

@Repository("productDao")
public class JpaProductDao extends GenericDaoImpl<Product, Long> implements ProductDao {

第二:

  @Bean 
  ProductDao getProductDao() {
    return new JpaProductDao();
  }

这就是为什么错误说您有多个实例并且容器不知道要注入哪个实例。

【讨论】:

  • 没有。该错误表明它没有找到任何实例。
  • 也许您需要使用 ProductDao productDao 来限定您的 @Autowired 依赖;
猜你喜欢
  • 1970-01-01
  • 2015-03-27
  • 2016-11-17
  • 2016-11-30
  • 1970-01-01
  • 2019-08-18
  • 2013-11-19
  • 1970-01-01
  • 2019-03-11
相关资源
最近更新 更多