字段XXX需要找不到类型为XXX的bean

时间:2018-06-22 17:24:24

标签: java spring-boot

我在Spring Boot中出错

2018-06-23 00:51:20.240  INFO 2053 --- [  restartedMain] org.tyrik.toys.App                       : Starting App on promote.cache-dns.local with PID 2053 (/Volumes/Lab/toys/target/classes started by tyrik in /Volumes/Lab/toys)
2018-06-23 00:51:20.242  INFO 2053 --- [  restartedMain] org.tyrik.toys.App                       : No active profile set, falling back to default profiles: default
2018-06-23 00:51:20.284  INFO 2053 --- [  restartedMain] ConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@40959417: startup date [Sat Jun 23 00:51:20 CST 2018]; root of context hierarchy
2018-06-23 00:51:21.267  INFO 2053 --- [  restartedMain] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$2f930cf8] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2018-06-23 00:51:21.583  INFO 2053 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8888 (http)
2018-06-23 00:51:21.607  INFO 2053 --- [  restartedMain] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2018-06-23 00:51:21.607  INFO 2053 --- [  restartedMain] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.31
2018-06-23 00:51:21.611  INFO 2053 --- [ost-startStop-1] o.a.catalina.core.AprLifecycleListener   : The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [/Users/tyrik/Library/Java/Extensions:/Library/Java/Extensions:/Network/Library/Java/Extensions:/System/Library/Java/Extensions:/usr/lib/java:.]
2018-06-23 00:51:21.701  INFO 2053 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2018-06-23 00:51:21.701  INFO 2053 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1419 ms
2018-06-23 00:51:21.827  INFO 2053 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Servlet dispatcherServlet mapped to [/]
2018-06-23 00:51:21.830  INFO 2053 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
2018-06-23 00:51:21.831  INFO 2053 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2018-06-23 00:51:21.831  INFO 2053 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2018-06-23 00:51:21.831  INFO 2053 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
2018-06-23 00:51:21.831  INFO 2053 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'corsFilter' to: [/*]
2018-06-23 00:51:21.992  INFO 2053 --- [  restartedMain] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'default'
2018-06-23 00:51:22.003  INFO 2053 --- [  restartedMain] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [
    name: default
    ...]
2018-06-23 00:51:22.056  INFO 2053 --- [  restartedMain] org.hibernate.Version                    : HHH000412: Hibernate Core {5.2.17.Final}
2018-06-23 00:51:22.057  INFO 2053 --- [  restartedMain] org.hibernate.cfg.Environment            : HHH000206: hibernate.properties not found
2018-06-23 00:51:22.180  INFO 2053 --- [  restartedMain] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
2018-06-23 00:51:22.266  INFO 2053 --- [  restartedMain] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2018-06-23 00:51:23.110  INFO 2053 --- [  restartedMain] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
2018-06-23 00:51:23.121  INFO 2053 --- [  restartedMain] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
2018-06-23 00:51:23.955  INFO 2053 --- [  restartedMain] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2018-06-23 00:51:23.973  WARN 2053 --- [  restartedMain] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'moduleController' defined in file [/Volumes/Lab/toys/target/classes/org/tyrik/toys/api/ModuleController.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.tyrik.toys.service.ModuleService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
2018-06-23 00:51:23.973  INFO 2053 --- [  restartedMain] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2018-06-23 00:51:23.974  INFO 2053 --- [  restartedMain] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown initiated...
2018-06-23 00:51:24.244  INFO 2053 --- [  restartedMain] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown completed.
2018-06-23 00:51:24.249  INFO 2053 --- [  restartedMain] o.apache.catalina.core.StandardService   : Stopping service [Tomcat]
2018-06-23 00:51:24.264  INFO 2053 --- [  restartedMain] ConditionEvaluationReportLoggingListener : 

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2018-06-23 00:51:24.371 ERROR 2053 --- [  restartedMain] o.s.b.d.LoggingFailureAnalysisReporter   : 

***************************
APPLICATION FAILED TO START
***************************

Description:

Parameter 0 of constructor in org.tyrik.toys.api.ModuleController required a bean of type 'org.tyrik.toys.service.ModuleService' that could not be found.


Action:

Consider defining a bean of type 'org.tyrik.toys.service.ModuleService' in your configuration.


Process finished with exit code 0

moduleContraller

@RestController
@RequestMapping("/module")
@Validated
public class ModuleController {
    private Logger log = LoggerFactory.getLogger(this.getClass());

    private final ModuleService moduleService;

    private final ResultGenerator generator;

    @Autowired
    public ModuleController(ModuleService moduleService, ResultGenerator generator) {
        this.moduleService = moduleService;
        this.generator = generator;
    }
    @PostMapping("/add")
    public RestResult addModule(@Valid Module module){

        return generator.getSuccessResult("添加模块成功", moduleService.saveModule(module));

    }

    @GetMapping("/all")
    public RestResult getModule(){
        return generator.getSuccessResult("查找成功", moduleService.getModule());
    }

    @GetMapping("/{id}")
    public RestResult getModuleByMID(@PathVariable("id") Integer MID){
        return generator.getSuccessResult("查找成功", moduleService.getModuleByMID(MID));

    }

    @PutMapping("/edit/{id}")
    public RestResult editModule(@PathVariable("id") Integer MID, String title, String description){
        return generator.getSuccessResult("修改成功", moduleService.editModule(MID, title, description));
    }

    @DeleteMapping("/remove/{id}")
    public void removeModule(@PathVariable("id")Integer MID) {
        moduleService.removeModuleByID(MID);
    }
}

ModuleRepository

package org.tyrik.toys.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import org.tyrik.toys.entity.Module;

@Repository
public interface ModuleRepository extends JpaRepository<Module, Integer> {

}

这里还有ModuleService

/**
 * 模块接口
 */
public interface ModuleService {
    Module saveModule(Module module);

    List<Module> getModule();

    Optional<Module> getModuleByMID(Integer MID);

    Module editModule(Integer MID, String title, String description);

    void removeModuleByID(Integer MID);
}

ModuleServiceImpl在这里

@Service("ModuleService")
public class ModuleServiceImpl implements ModuleService{
   @Autowired
    ModuleRepository moduleRepository;
    private Module moudle;

    @Override
    public Module saveModule(Module module) {
        return moduleRepository.save(module);
    }

    @Override
    public List<Module> getModule() {
        return moduleRepository.findAll();
    }

    @Override
    public Optional<Module> getModuleByMID(Integer MID) {
        return moduleRepository.findById(MID);
    }

    @Override
    public Module editModule(Integer MID, String title, String description) {
        Module m = new Module();
        m.setMID(MID);
        m.setTitle(title);
        m.setDescription(description);
        return moduleRepository.save(m);
    }

    @Override
    public void removeModuleByID(Integer MID) {
        moduleRepository.deleteById(MID);
    }    
}

现在我无法入睡。这个问题困扰了我整整一整天,希望你们能帮助我解决问题。

3 个答案:

答案 0 :(得分:0)

您在“应用程序”上下文中没有服务。可能的错误是 您的主类没有附加@EnableAutoConfiguration注释。

如果要测试此错误,只需在主类中创建此Bean:

@Bean
public ModuleService moduleService(ModuleRepository moduleRepository) {
    return new ModuleServiceImpl(moduleRepository);
}

答案 1 :(得分:0)

您能否检查主类是否已定义ComponentScan或将basePackages传递给SpringBootApplication批注?不带任何包的@SpringBootApplication应该也可以工作,因为您将App.java放在了父包上。

答案 2 :(得分:0)

ModuleServiceImpl 删除“ ModuleServiceImpl ” bean名称。由于您只有ModuleService接口的一种实现,因此限定在这里不需要。

@Service
public class ModuleServiceImpl implements ModuleService{

如果您仍然要使用bean名称,请尝试使用@Qualifier

@Autowired
public ModuleController(@Qualifier(ModuleServiceImpl) ModuleService moduleService, ResultGenerator generator) 
{
    this.moduleService = moduleService;
    this.generator = generator;
}