简体   繁体   中英

Trying to connect JPA with spring controller but getting: 'Error creating bean with name 'mainController': Unsatisfied dependency expressed through..'

I created Spring MVC application like in this: link , things worked and every thing was good. Then, I added the JPA to connect the application to database like in this link , but I am getting the following error:

Root Cause

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'mainController': Unsatisfied dependency expressed through field 'userService'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.testtask.spring.service.UserService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:643)
    org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:116)
    org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:399)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1422)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:594)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517)
    org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323)
    org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321)
    org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
    org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:879)
    org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:878)
    org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550)
    org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:702)
    org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:668)
    org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:716)
    org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:591)
    org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:530)
    org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:170)
    javax.servlet.GenericServlet.init(GenericServlet.java:158)
    org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542)
    org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
    org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:687)
    org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357)
    org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:374)
    org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
    org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:893)
    org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1707)
    org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1130)
    java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:630)
    org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)

This is my controller class:

@Controller
@Configuration
@ComponentScan("com.testtask.spring.controller")
public class MainController {
    
    @Autowired
    private UserService userService;
    
    @RequestMapping("/welcome")
    public ModelAndView helloWorld() {
        
        System.out.println("Hi this is Tasneem");
        
        String message = "<br><div style='text-align:center;'>"
                + "<h3>******** Hello World, Spring MVC Tutorial</h3> This message is coming "
                + "from the controller ***********</div><br><br>";
        
        List<Statement> test = userService.findRecordsByAccountId(4L);
        if(test != null && test.size() > 0) {
            System.out.println(test.get(0).getAccountId());
            System.out.println(test.get(0).getDateField());
            System.out.println(test.get(0).getAmount());
            
        }
        
        return new ModelAndView("welcome", "message", message);
    }
    

}

and this is my Service implementation class:

@Component
@Service
public class UserServiceImpl implements UserService{

    @Autowired
    UserRepository userRepository;
    
    @Override
    public boolean findUserByUsernameAndPassword(String username, String password) {
        return userRepository.findByUsernameAndPassword(username, password);
    }

    @Override
    public List<Statement> findRecordsByAccountId(Long accountId) {
        return userRepository.getRecordsByAccountId(4L);
    }

}

I am attaching the github link: https://github.com/tabusharkh/spring-mvc-primefaces .

Given that you don't have a class at the main package level, you will need to include all relevant packages in the @ComponentScan annotation:

@Controller
@ComponentScan({"com.testtask.spring.controller", "com.testtask.spring.serviceImpl", "com.testtask.spring.repoImpl"})
public class MainController {
    (...)
}

Additionally, you don't need @Component and @Service in UserServiceImpl , just use one of them:

@Service
public class UserServiceImpl implements UserService{
     (...)
}

You can read more about this at the following online resource: https://www.baeldung.com/spring-component-repository-service .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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