春季自动装配错误

Posted

技术标签:

【中文标题】春季自动装配错误【英文标题】:Error Coming in Autowiring in Spring 【发布时间】:2017-12-13 07:43:56 【问题描述】:

我已经在组件扫描和@component 中输入了包名称,但仍然出现错误。代码如下。

这里是 SpringConfig 文件:-

@Configuration
@ComponentScan(basePackages="com.cagataygurturk.example.lambda","com.cagataygurturk.example.services")
public class SpringConfig 


这是服务类:-

@Component
public class Service 

    /**
     * Autowiring another Spring Bean
     */
    @Autowired
    AnotherService anotherService;

    public String getText(String text) 
        //return anotherService.getText(text);
        return "hello";
    

这是在服务类中自动装配的另一个服务类:-

@Component
public class AnotherService 
    @Autowired
    IFileStoreService file;
    public String getText(String text) 
        String t;
        t=(String)text;
        if(t.equals("get"))
        
            file.get("1");
            return "You are in Get Controller and database is not connected\n";
        
        else
        if(t=="post")
        
            return "You are in post Controller and databse is not connecte\n";
        
        else
        if(t=="delete")
        
            return "You are int delete Controller and mongo database in not connected\n";
        
        else
        
            return "hii\n"+text+"hey";
        
    

这是在 AnotherService 类中自动装配的 IFileStoreService 类:

public interface IFileStoreService 
Resource get(String id) throws StorageException, StorageFileNotFoundException;

这是 IFileStoreImpl 类:-

@Component
public class FileStoreServiceImpl implements IFileStoreService 
    private static final Logger logger = LoggerFactory.getLogger(FileStoreServiceImpl.class);

    @Autowired
    private IFileStoreDAO fileStoreDAO;

    @Autowired
    private StorageProperties storageProperties;


    @Override
    public Resource get(String id) throws StorageException, StorageFileNotFoundException 
        Resource resource = null;
        File file = null;
        try 
            FileDetails fileDetails = fileStoreDAO.get(id);
            if(fileDetails != null) 
                String tempDir = storageProperties.getLocation();
                file = new File(tempDir + File.separator + fileDetails.getName());
                file.mkdirs();
                if(file.exists()) 
                    // p1: delete any file if existent in the directory;
                    file.delete();
                
                file.createNewFile();
                FileCopyUtils.copy(fileDetails.getFileBytes(), file);
                resource = new UrlResource(Paths.get(tempDir).resolve(fileDetails.getName()).toUri());
             else 
                throw new  StorageFileNotFoundException("No document found with id: " + id);
            
         catch (Exception e) 
            logger.error(e.getMessage(), e);
            if (e instanceof StorageFileNotFoundException) 
                throw (StorageFileNotFoundException) e;
             else 
                throw new StorageException("", e);
            
        
        return resource;
    

最后一个 MainHandler 函数:-

@SuppressWarnings("unused")
public class MainHandler
        extends AbstractHandler<SpringConfig>
        implements RequestHandler<Map<String,Object>, String> 

    static final Logger log = Logger.getLogger(MainHandler.class);
    @Override
    public String handleRequest(Map<String, Object> input, Context context)throws RuntimeException 
        // TODO Auto-generated method stub
        Service businessService = getApplicationContext().getBean(Service.class);
        return businessService.getText("hii");

    

错误是:-

"errorMessage":"Error creating bean with name 'service': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.cagataygurturk.example.services.AnotherService com.cagataygurturk.example.services.Service.anotherService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'anotherService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.cagataygurturk.example.services.IFileStoreService com.cagataygurturk.example.services.AnotherService.file; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'fileStoreServiceImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.cagataygurturk.example.services.IFileStoreDAO com.cagataygurturk.example.services.FileStoreServiceImpl.fileStoreDAO; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.cagataygurturk.example.services.IFileStoreDAO] 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)","errorType":"org.springframework.beans.factory.BeanCreationException"

【问题讨论】:

请尝试使用@Component而不是实现来注释接口(IFileStoreService) 完成了,但仍然会出现同样的错误 好的,抱歉,我误读了错误。我认为问题的根源是我认为最后一次失败的依赖注入。错误的最后一部分说:No qualifying bean of type [com.cagataygurturk.example.services.IFileStoreDAO]。你确定IFileStoreDAO 类(你没有在这里发布)在组件扫描下,并且注释正确吗? 那个接口有实现类吗? 感谢 maydawn ,"@component" 在 IFileStoreDAO 的实现类中。但是为什么在创建服务类的bean时会显示错误? 【参考方案1】:

正如异常堆栈跟踪所暗示的那样:

No qualifying bean of type [com.cagataygurturk.example.services.IFileStoreDAO] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency.

这意味着 IFileStoreDAO 类没有实现(我对此不是 100% 确定,可能会得到不同的异常),或者缺少 @Component 注释,或者 Spring 没有将其作为组件扫描位于未在 @ComponentScan(basePackages="com.cagataygurturk.example.lambda","com.cagataygurturk.example.services") 下声明的包中。

有关Spring Boot组件扫描的更多信息,请参见此答案:https://***.com/a/33619632/5229041

【讨论】:

以上是关于春季自动装配错误的主要内容,如果未能解决你的问题,请参考以下文章

春季自动装配有啥好处

创建名为“homeController”的 bean 时出错:自动装配依赖项的注入失败

为啥自动装配的 bean 为空?

如何使用 Mockito 在 Spring 中模拟自动装配的 @Value 字段?

具有自动装配的字段但得到无法自动装配字段消息

注入自动装配的依赖项失败,无法自动装配字段