0

I am new to spring MVC annotation, but I am getting this exception

 WARNING: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'appConfig': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.websystique.springmvc.converter.RoleToUserProfileConverter com.websystique.springmvc.configuration.AppConfig.roleToUserProfileConverter; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'roleToUserProfileConverter': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.websystique.springmvc.service.UserProfileService com.websystique.springmvc.converter.RoleToUserProfileConverter.userProfileService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.websystique.springmvc.service.UserProfileService] 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)}

AppConfig

 package com.websystique.springmvc.configuration;

 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.context.MessageSource;
 import org.springframework.context.annotation.Bean;
 import org.springframework.context.annotation.ComponentScan;
 import org.springframework.context.annotation.Configuration;
 import org.springframework.context.support.ResourceBundleMessageSource;
 import org.springframework.format.FormatterRegistry;
 import org.springframework.stereotype.Component;
 import org.springframework.web.servlet.config.annotation.EnableWebMvc;

import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import 
 org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
 import 
  org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
  import 
  org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
 import org.springframework.web.servlet.view.InternalResourceViewResolver;
 import org.springframework.web.servlet.view.JstlView;

 import com.websystique.springmvc.converter.RoleToUserProfileConverter;


 @Configuration
  @Component
  @EnableWebMvc
   @ComponentScan(basePackages = "com.websystique.springmvc.converter")
   public class AppConfig extends WebMvcConfigurerAdapter{


            @Autowired
            RoleToUserProfileConverter roleToUserProfileConverter;


            /**
             * Configure ViewResolvers to deliver preferred views.
             */
            @Override
            public void configureViewResolvers(ViewResolverRegistry registry) {

                InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
                viewResolver.setViewClass(JstlView.class);
                viewResolver.setPrefix("/WEB-INF/views/");
                viewResolver.setSuffix(".jsp");
                registry.viewResolver(viewResolver);
            }

            /**
             * Configure ResourceHandlers to serve static resources like CSS/ Javascript etc...
             */
            @Override
            public void addResourceHandlers(ResourceHandlerRegistry registry) {
                registry.addResourceHandler("/static/**").addResourceLocations("/static/");
            }

            /**
             * Configure Converter to be used.
             * In our example, we need a converter to convert string values[Roles] to UserProfiles in newUser.jsp
             */
            @Override
            public void addFormatters(FormatterRegistry registry) {
                registry.addConverter(roleToUserProfileConverter);
            }


            /**
             * Configure MessageSource to lookup any validation/error message in internationalized property files
             */
            @Bean
            public MessageSource messageSource() {
                ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
                messageSource.setBasename("messages");
                return messageSource;
            }

            /**Optional. It's only required when handling '.' in @PathVariables which otherwise ignore everything after last '.' in @PathVaidables argument.
             * It's a known bug in Spring [https://jira.spring.io/browse/SPR-6164], still present in Spring 4.1.7.
             * This is a workaround for this issue.
             */
            @Override
            public void configurePathMatch(PathMatchConfigurer matcher) {
                matcher.setUseRegisteredSuffixPatternMatch(true);
            }
        }

RoleToUserProfileConverter

  package com.websystique.springmvc.converter;

  import org.slf4j.Logger;
  import org.slf4j.LoggerFactory;
  import org.springframework.beans.factory.annotation.Autowired;
  import org.springframework.core.convert.converter.Converter;
  import org.springframework.stereotype.Component;

  import com.websystique.springmvc.model.UserProfile;
  import com.websystique.springmvc.service.UserProfileService;

           **
           * A converter class used in views to map id's to actual userProfile objects.
           */
           Component
           public class RoleToUserProfileConverter implements Converter<Object, UserProfile>{

            static final Logger logger = LoggerFactory.getLogger(RoleToUserProfileConverter.class);

            @Autowired
            UserProfileService userProfileService;

            /**
             * Gets UserProfile by Id
             * @see org.springframework.core.convert.converter.Converter#convert(java.lang.Object)
             */
            public UserProfile convert(Object element) {
                Integer id = Integer.parseInt((String)element);
                UserProfile profile= userProfileService.findById(id);
                logger.info("Profile : {}",profile);
                return profile;
            }

I tried many solutions given in this site with this link also this

I have run out of ideas, anything that might help ? It is just basic web application and I am still struggling with this, I have added the exact package name in the component scan and stil I am facing this issue.

1 Answers1

0

The exception indicates the reason for failure to autowire the nested dependency.

No qualifying bean of type [com.websystique.springmvc.service.UserProfileService] found for dependency:
expected at least 1 bean which qualifies as autowire candidate for this dependency.

Spring is not able to find a bean of type com.websystique.springmvc.service.UserProfileService

You need to add either the Component that is of type com.websystique.springmvc.service.UserProfileService via @Import or via @ComponentScan.

One such solution:

Assuming the Component is in package com.websystique.springmvc.service, you may change your @ComponentScan as follows:

e.g.

...
@ComponentScan({"com.websystique.springmvc.converter", "com.websystique.springmvc.service"})
public class AppConfig extends WebMvcConfigurerAdapter{
  ...
}

Change the package name accordingly depending on where the UserProfileService bean resides.

Neo
  • 4,640
  • 5
  • 39
  • 53