1
votes

Why Injection of autowired dependencies failed.

SEVERE: Context initialization failed org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'homeController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.quickstart.com.springmvc.service.UserService com.quickstart.com.springmvc.controller.HomeController.userservice; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.quickstart.com.springmvc.service.UserService] 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:287) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1106)

MvcConfiguration.java

package com.quickstart.com.springmvc.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.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

@Configuration
@ComponentScan(basePackages="com.quickstart.com.springmvc")
@EnableWebMvc
public class MvcConfiguration extends WebMvcConfigurerAdapter{

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

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
    }
}

HomeController.java

package com.quickstart.com.springmvc.controller;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.quickstart.com.springmvc.model.User;
import com.quickstart.com.springmvc.service.UserService;

@Controller

public class HomeController {

    @Autowired
    UserService userservice;

    @RequestMapping(value="/ved")
    public ModelAndView test(HttpServletResponse response) throws IOException{
        System.out.println("home");
        return new ModelAndView("home");
    }

    @RequestMapping(value="/myfun")

    public ModelAndView fun(HttpServletResponse response) throws IOException {
        System.out.println("myfun");
        return new ModelAndView();
    }

    @RequestMapping(value="/user/" , method=RequestMethod.GET)
    public ResponseEntity<List<User>> listAllUser() {

        List<User> users = userservice.findAllUsers();
        System.out.println("ammm");
        if(users.isEmpty()){
            return new ResponseEntity<List<User>>(HttpStatus.NO_CONTENT);
        }

        else{
            return new ResponseEntity<List<User>>(users,HttpStatus.OK);
        }
    }
}

User.java

package com.quickstart.com.springmvc.model;

public class User {

    private int id;

    private String name;

    private String email;

    private int age;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

userSerive.java

package com.quickstart.com.springmvc.service;

import java.util.List;

import org.springframework.context.annotation.Bean;

import com.quickstart.com.springmvc.model.User;


public interface UserService {

    User findById(long id);

    User findByName(String name);

    void saveUser(User user);

    void updateUser(User user);

    void deleteUserById(long id);

    List<User> findAllUsers(); 

    void deleteAllUsers();

    public boolean isUserExist(User user);

}

UserServiceImpl.java

package com.quickstart.com.springmvc.service;

import java.util.List;

import org.springframework.stereotype.Service;

import com.quickstart.com.springmvc.model.User;

@Service("userService")
public class UserServiceImpl implements UserService {

    private List<User> user;

    /*User findById(long id){

        return User;
    }*/

    List<User> findAllUsers(){
        System.out.println("my implemetion");

        return user;
    }

}

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
    <display-name>springmvc</display-name>
    <context-param>
        <param-name>contextClass</param-name>
        <param-value>
            org.springframework.web.context.support.AnnotationConfigWebApplicationContext
        </param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <servlet>
        <servlet-name>SpringDispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextClass</param-name>
            <param-value>
                org.springframework.web.context.support.AnnotationConfigWebApplicationContext
            </param-value>
        </init-param>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>com.quickstart.com.springmvc</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>SpringDispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <session-config>
        <session-timeout>30</session-timeout>
    </session-config>
</web-app>
1
Please, attach your UserService Class with the questionsunkuet02
@sunkuet02 just a second i will be updateGolu Sharma
you have to enable the annotation configuration this link will help[stackoverflow.com/questions/15158046/…Akshay jain
I have run your given code successfully by adding methods in UserServiceImpl class which are not declared.sunkuet02
@sunkuet02 yes: i made very dump mistake in my service. Because public class UserServiceImpl implements UserService. I did not implement with userService. I fixed my mistake. and Thank you from my bottom of my heartGolu Sharma

1 Answers

1
votes

I run your code on my machine. Everything is fine. Please check below line and learn more about @Service and @Autowiring

add @Service annotation above your userService and implement it properly.