java - @Repository 的 @Autowire 失败

标签 java spring

我是一名java开发人员,正在使用公司所需的自定义框架,该框架基于spring。我设法让旧版本工作,但这个新版本的 @Repository 有问题,尽管 bean 正在被扫描,但它不能是 @Autowired。

这是错误

    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 'jobInvoiceServiceImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private foo.repository.impl.JobInvoiceRepositoryImpl foo.service.impl.JobInvoiceServiceImpl.jobInvoiceRepositoryImpl; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [foo.repository.impl.JobInvoiceRepositoryImpl] 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:1214)
    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:772)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:839)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:538)
    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:444)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:326)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:5003)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5517)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1574)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1564)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private foo.repository.impl.JobInvoiceRepositoryImpl foo.service.impl.JobInvoiceServiceImpl.jobInvoiceRepositoryImpl; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [foo.repository.impl.JobInvoiceRepositoryImpl] 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:573)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
    ... 22 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [foo.repository.impl.JobInvoiceRepositoryImpl] 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:1373)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1119)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1014)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:545)
    ... 24 more

Aug 15, 2016 5:09:17 PM com.sun.faces.config.ConfigureListener contextInitialized
INFO: Initializing Mojarra 2.2.5 ( 20140108-1427 https://svn.java.net/svn/mojarra~svn/tags/2.2.5@12761) for context '/invoicer-application-war'
0    [localhost-startStop-1] WARN  org.springframework.web.context.support.XmlWebApplicationContext  - Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jobInvoiceServiceImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private foo.repository.impl.JobInvoiceRepositoryImpl foo.service.impl.JobInvoiceServiceImpl.jobInvoiceRepositoryImpl; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [foo.repository.impl.JobInvoiceRepositoryImpl] 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)}
19   [localhost-startStop-1] ERROR org.springframework.web.context.ContextLoader  - Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jobInvoiceServiceImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private foo.repository.impl.JobInvoiceRepositoryImpl foo.service.impl.JobInvoiceServiceImpl.jobInvoiceRepositoryImpl; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [foo.repository.impl.JobInvoiceRepositoryImpl] 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:1214)
    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:772)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:839)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:538)
    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:444)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:326)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:5003)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5517)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1574)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1564)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private foo.repository.impl.JobInvoiceRepositoryImpl foo.service.impl.JobInvoiceServiceImpl.jobInvoiceRepositoryImpl; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [foo.repository.impl.JobInvoiceRepositoryImpl] 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:573)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
    ... 22 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [foo.repository.impl.JobInvoiceRepositoryImpl] 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:1373)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1119)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1014)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:545)
    ... 24 more

这是应用程序代码:

@ Controller

package foo.controller;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;

import foo.domain.JobInvoiceBean;
import foo.service.impl.JobInvoiceServiceImpl;

@SuppressWarnings("unused")
@Component
@Scope("view")
public class InvoiceSearchController implements Serializable {

    private static final long serialVersionUID = -1124694025090601008L;

    private List<JobInvoiceBean> jobInvoiceList = new ArrayList<JobInvoiceBean>();
    private List<JobInvoiceBean> filteredJobInvoices = new ArrayList<JobInvoiceBean>();

    private JobInvoiceBean selectedJobInvoice;

    @Autowired
    private JobInvoiceServiceImpl jobInvoiceServiceImpl;

    public void init() {
        List<JobInvoiceBean> jobInvoiceList = jobInvoiceServiceImpl.getAllJobInvoice();
    }


//  public void getJobInvoiceDetail() {
//      getJobInvoiceDetail(this.selectedJobInvoice);
//  }
//  
//  private void getJobInvoiceDetail(JobInvoiceBean jobInvoiceBean){
//      //This is essentially just a re-fetch
//      JobInvoiceBean jobInvoice = jobInvoiceService.findJobInvoiceById(jobInvoiceBean.getInvoiceNo());
//      
//      jobInvoiceBean = jobInvoice;
//  }

    /*
    public void onPropertyEdit(CellEditEvent event) {

        DataTable dataTable = (DataTable) event.getSource();
        PropertyBean modifiedProperty = (PropertyBean) dataTable.getRowData();

        Property property = jobInvoiceService.findPropertyById(modifiedProperty.getId());
        BeanUtils.copyProperties(modifiedProperty, property, "surface", "addresses");
        property.setSurface(BigDecimal.valueOf(modifiedProperty.getSurface()));

        jobInvoiceService.saveOrUpdateProperty(property);

        FacesMessage msg = new FacesMessage(
                getBundleMessage("property.edition.message"),
                modifiedProperty.getName());
        FacesContext.getCurrentInstance().addMessage(null, msg);
    }

    */

    public JobInvoiceBean getSelectedJobInvoice() {
        return selectedJobInvoice;
    }

    public void setSelectedJobInvoice(JobInvoiceBean selectedJobInvoice) {
        this.selectedJobInvoice = selectedJobInvoice;
    }


    public List<JobInvoiceBean> getJobInvoiceList() {
        return jobInvoiceList;
    }


    public void setJobInvoiceList(List<JobInvoiceBean> jobInvoiceList) {
        this.jobInvoiceList = jobInvoiceList;
    }


    public List<JobInvoiceBean> getFilteredJobInvoices() {
        return filteredJobInvoices;
    }


    public void setFilteredJobInvoices(List<JobInvoiceBean> filteredJobInvoices) {
        this.filteredJobInvoices = filteredJobInvoices;
    }


}

@服务

package foo.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import foo.domain.JobInvoiceBean;
import foo.repository.impl.JobInvoiceRepositoryImpl;
import foo.service.JobInvoiceService;

@Service
public class JobInvoiceServiceImpl implements JobInvoiceService {

    @Autowired
    private JobInvoiceRepositoryImpl jobInvoiceRepositoryImpl;

    @Override
    public List<JobInvoiceBean> getAllJobInvoice() {
        return jobInvoiceRepositoryImpl.getAllInvoices();
    }

}

@存储库

package foo.repository.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.sql.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.core.convert.ConversionService;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.simple.SimpleJdbcCall;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import foo.domain.JobInvoiceBean;
import foo.repository.CustomJobInvoiceRepository;

@Transactional(readOnly = true)
@SuppressWarnings("unchecked")
@Repository
public class JobInvoiceRepositoryImpl implements CustomJobInvoiceRepository {

    private static final Logger LOGGER = LoggerFactory.getLogger(JobInvoiceRepositoryImpl.class);

    private BeanPropertyRowMapper<JobInvoiceBean> invoiceRowMapper;

    private SimpleJdbcCall simpleJdbcCall;
    private DataSource dataSource;

    @Override
    public List<JobInvoiceBean> getAllInvoices() {
        List<JobInvoiceBean> listInvoice = new ArrayList<JobInvoiceBean>();
        try{
            simpleJdbcCall = new SimpleJdbcCall(dataSource);

            simpleJdbcCall.withCatalogName("invoicer_pkg")
                        .withFunctionName("get_job_invs")
                        .returningResultSet("ret_cursor", invoiceRowMapper);

//          SqlParameterSource in = new MapSqlParameterSource()
//              .addValue("clientReference", clientReference)
//              .addValue("hasChildren", hasChildren ? "Y" : "N");

            Map<String, Object> result = simpleJdbcCall.execute();          

            if (result != null && result.size() > 0) {
                listInvoice = (List<JobInvoiceBean>) result.get("ret_cursor");
            }

        } catch (Exception e) {
            LOGGER.error(e.getMessage());
        }       
        return listInvoice;
    }

    @Autowired
    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    @Autowired
    public void setConversionService(final ConversionService conversionService) {
        this.invoiceRowMapper = new BeanPropertyRowMapper<JobInvoiceBean>(JobInvoiceBean.class);        
    }
}

我可能错过了一些东西,但我看不到它。

提前致谢。

最佳答案

您的 JobInvoiceRepositoryImpl 类实现 CustomJobInvoiceRepository 接口(interface)并使用 @Transactional 进行注释。

Spring AOP 事务基础架构检测其事务性并创建一个事务性 JDK 代理,该代理实现 CustomJobInvoiceRepository 并委托(delegate)给 JobInvoiceRepositoryImpl。

应用程序上下文中的实际 bean 不再是 JobInvoiceRepositoryImpl,而是一个代理。

您不能注入(inject) JobInvoiceRepositoryImpl,而是使用如下接口(interface)

@Service
public class JobInvoiceServiceImpl implements JobInvoiceService {

    @Autowired
    private CustomJobInvoiceRepository jobInvoiceRepository;

    @Override
    public List<JobInvoiceBean> getAllJobInvoice() {
        return jobInvoiceRepository.getAllInvoices();
    }

}

否则指示 Spring 使用 CGLIB 例如基于类的代理

@EnableTransactionManagement(proxyTragetClass = true) 

或 xml 中的等效项

<tx:annotation-driven proxy-target-class="true"/>

关于java - @Repository 的 @Autowire 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38958985/

相关文章:

java - 方法命名中的 Spring 'NOT IN' 未按预期工作

spring - 过滤器嵌套数组 Spring elasticsearch

java - 如何在 Spring Data Rest 上的 GET/find 中对实体进行计算?

java - 无法加载标签 "org.apache.struts2.views.jsp.ui.FormTag"的标签处理程序类 "s:form"

java - 如何获取编译器编译一个类所需的所有源的列表

Java 8 List<T> 到 Map<T, (index)>

java - Spring MVC 和 "magic string"返回类型

Java:用整数替换字符串

java - 如何在 JNI 中将指针从 java 传递到 C?

Spring MVC 与 JAXB,基于通用类的列表响应