简体   繁体   English

Spitter不满意的依赖异常Spring MVC

[英]Spitter Unsatisfied Dependency Exception Spring MVC

I starting in Spring MVC with the Book Spring in Action, I'm making the exercise of the chapter 5, with the Spitter application but I got the following error: 我在Spring MVC中使用Book Spring in Action开始,我正在练习第5章,使用Spitter应用程序,但是我收到了以下错误:

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'spittleController' defined in file [C:\\xampp\\htdocs.metadata.plugins\\org.eclipse.wst.server.core\\tmp1\\wtpwebapps\\spitter\\WEB-INF\\classes\\com\\spitter\\web\\SpittleController.class]: Unsatisfied dependency expressed through constructor argument with index 0 of type [com.spitter.data.SpittleRepository]: : No qualifying bean of type [com.spitter.data.SpittleRepository] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. org.springframework.beans.factory.UnsatisfiedDependencyException:在文件[C:\\ xampp \\ htdocs.metadata.plugins \\ org.eclipse.wst.server.core \\ tmp1 \\ wtpwebapps \\ spitter \\ WEB中定义的名称为“spittleController”的bean创建时出错-INF \\ classes \\ com \\ spitter \\ web \\ SpittleController.class]:通过构造函数参数表示的不满意的依赖关系,类型为[com.spitter.data.SpittleRepository]的索引0 ::没有类型为[com.spitter.data的限定bean]。 SpittleRepository]发现依赖:预期至少有1个bean可以作为此依赖项的autowire候选者。 Dependency annotations: {}; 依赖注释:{}; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.spitter.data.SpittleRepository] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. 嵌套异常是org.springframework.beans.factory.NoSuchBeanDefinitionException:没有为依赖项找到类型为[com.spitter.data.SpittleRepository]的限定bean:期望至少有一个bean可以作为此依赖项的autowire候选者。 Dependency annotations: {} 依赖注释:{}

I got the project here in github: https://github.com/kevingcfcb88/spitter.git 我在github上找到了这个项目: https//github.com/kevingcfcb88/spitter.git

I already do my research but nothing seems to work. 我已经做了我的研究,但似乎没有任何效果。

I'm using STS and Maven, this is the structure of the app: 我正在使用STS和Maven,这是应用程序的结构:

项目结构

Here is my pom.xml 这是我的pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.spitter.config</groupId>
<artifactId>spitter</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>

<name>spitter</name>
<url>http://maven.apache.org</url>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <springframework.version>4.1.5.RELEASE</springframework.version>
</properties>

<dependencies>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>3.8.1</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>${springframework.version}</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.1.0</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet.jsp</groupId>
        <artifactId>javax.servlet.jsp-api</artifactId>          
        <version>2.3.1</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-lang3</artifactId>
        <version>3.0</version>
    </dependency>

</dependencies>

<build>
    <pluginManagement>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.2</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.4</version>
                <configuration>
                    <warSourceDirectory>src/main/webapp</warSourceDirectory>
                    <warName>spitter</warName>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
        </plugins>
    </pluginManagement>
    <finalName>spitter</finalName>
</build>

And my config files: 我的配置文件:

SpittrWebAppInitializer.java SpittrWebAppInitializer.java

 package com.spitter.config;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class SpittrWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer{

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

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

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

}

WebConfig.java WebConfig.java

package com.spitter.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

@Configuration
@EnableWebMvc
@ComponentScan("com.spitter.web")
public class WebConfig extends WebMvcConfigurerAdapter {

    @Bean
    public ViewResolver viewResolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/views/");
        resolver.setSuffix(".jsp");
        resolver.setExposeContextBeansAsAttributes(true);
        return resolver;
    }

    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }

}

RootConfig.java RootConfig.java

package com.spitter.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScan.Filter;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

@Configuration
@ComponentScan(basePackages = { "com.spitter.data" }, excludeFilters = {@Filter(type = FilterType.ANNOTATION, value = EnableWebMvc.class) })
public class RootConfig {

}

As @mh-dev explained, you need an implementation of SpittleRepository . 正如@ mh-dev解​​释的那样,您需要SpittleRepository的实现。 Try adding this class and see if your code can run: 尝试添加此类,看看您的代码是否可以运行:

public class SpittleRepositoryImpl implements SpittleRepository {

  List <Spittle> findSpittles(long max, int count) {
    System.out.println("I need a real implementation! " 
      + "I received max as " + max + " and count as " + count + ".");
  }

}

I would suggest re-reading the relevant sections of the book to make sure you didn't miss anything. 我建议重新阅读本书的相关部分,以确保你没有遗漏任何东西。

You just need to add a repository implementation of SpittleRepository with @Repository in the header, because even though you have added implementation classes, spring IOC is unaware of actual dependency and the example in the book should have worked if you had put all the java files in the same package hierarchy with repository implementation. 你只需要在头文件中添加一个带有@Repository的SpittleRepository的存储库实现,因为即使你已经添加了实现类,spring IOC也不知道实际的依赖性,如果你把所有的java文件放在了本书中的例子应该有用在具有存储库实现的相同包层次结构中。

@Repository
public class SpittleRepositoryDAO implements SpittleRepository {

    public SpittleRepositoryDAO() {

    }

    @Override
    public List<Spittle> findSpittles(long max, int count) {
        List<Spittle> spittles = new ArrayList<Spittle>();
        for (int i = 0; i < count; i++) {
            spittles.add(new Spittle("Spittle " + i, new Date()));
        }
        return spittles;
    }
}

I know this code. 我知道这段代码。 It used to give me serious headache 2 years ago. 2年前它曾经给我带来严重的头痛。 The eror is in the code OR the book itslef. 错误在代码或书籍中。

Go to the publishers site and download the updated sourcecode. 转到发布者网站并下载更新的源代码。 here 这里

or 要么

https://www.manning.com/books/spring-in-action-fourth-edition https://www.manning.com/books/spring-in-action-fourth-edition

Here is the implementation of the repository: 以下是存储库的实现:

package com.spitter.web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.spitter.data.SpittleRepository;

@Controller
@RequestMapping("/spittles")
public class SpittleController {

    private SpittleRepository spittleRepository;

    @Autowired
    public SpittleController(SpittleRepository spittleRepository) {
        this.spittleRepository = spittleRepository;
    }

    @RequestMapping(method = RequestMethod.GET)
    public String spittles(Model model) {
        model.addAttribute("spittleList", spittleRepository.findSpittles(Long.MAX_VALUE, 20));
        return "spittles";
    }

}

yep, the problem is that you need an implementation of SpittleRepository . 是的,问题是你需要一个SpittleRepository的实现。 Cause you can't have an interface as bean, you know. 因为你知道,因为你不能把接口作为bean。 The scan component need at least one implementation of it and with the annotation @Component. 扫描组件至少需要一个实现,并且需要注释@Component。 That's it ;) 而已 ;)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM