春季注释:org.springframework.beans.factory.BeanCreationException

时间:2018-12-02 23:03:07

标签: spring

我是Spring MVC注释的新手,但是我遇到了这个异常

 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;
            }

我使用此link尝试了本网站提供的许多解决方案 also this

我的想法已经用光了,可能有什么帮助吗?这只是基本的Web应用程序,我仍在为此苦苦挣扎,我在遇到此问题的组件扫描中添加了确切的程序包名称。

1 个答案:

答案 0 :(得分:0)

该异常指示无法自动装配嵌套依赖项的原因。

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找不到com.websystique.springmvc.service.UserProfileService类型的bean

您需要通过com.websystique.springmvc.service.UserProfileService或通过@Import添加类型为@ComponentScan的组件。

一种解决方案:

假设组件位于软件包com.websystique.springmvc.service中,则可以如下更改@ComponentScan

例如

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

根据UserProfileService bean所在的位置,相应地更改程序包名称。