在Spring MVC中自动获取错误:创建名为'userService'的bean时出错:注入自动连接的依赖项

时间:2015-06-17 07:11:35

标签: spring-mvc jpa spring-boot

我有几天这个错误,似乎没有运气。尝试谷歌搜索,但仍然无法使其工作。在日志中查看它一直告诉我“注入自动连接的依赖项”有问题,但我无法得到它。希望收到你的来信。

错误日志。

        org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.sesame.repository.UserRepository com.sesame.service.UserService.userRepository; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.sesame.repository.UserRepository] 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:334)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1210)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
        at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:755)
        at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
        at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118)
        at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:686)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:320)
        at org.springframework.boot.context.web.SpringBootServletInitializer.run(SpringBootServletInitializer.java:117)
        at org.springframework.boot.context.web.SpringBootServletInitializer.createRootApplicationContext(SpringBootServletInitializer.java:108)
        at org.springframework.boot.context.web.SpringBootServletInitializer.onStartup(SpringBootServletInitializer.java:68)
        at org.springframework.web.SpringServletContainerInitializer.onStartup(SpringServletContainerInitializer.java:175)
        .......

控制器类

@Controller
@RequestMapping(value = "/protected/users")
public class UsersControl {
    private static final String DEFAULT_PAGE_DISPLAYED_TO_USER = "0";

    @Autowired
    private UserService userService;

    @Autowired
    private MessageSource messageSource;

    @Value("5")
    private int maxResults;

    @RequestMapping(method = RequestMethod.GET)
    public ModelAndView welcome() {
        return new ModelAndView("contactsList");
    }

    @RequestMapping(method = RequestMethod.GET, produces = "application/json")
    public ResponseEntity<?> listAll(@RequestParam int page, Locale locale) {
        return createListAllResponse(page, locale);
    }


    private UserListVO listAll(int page) {
        return userService.findAll(page, maxResults);
    }

    private ResponseEntity<UserListVO> returnListToUser(UserListVO contactList) {
        return new ResponseEntity<UserListVO>(contactList, HttpStatus.OK);
    }

    private ResponseEntity<?> createListAllResponse(int page, Locale locale) {
        return createListAllResponse(page, locale, null);
    }

    private ResponseEntity<?> createListAllResponse(int page, Locale locale, String messageKey) {
        UserListVO UserListVO = listAll(page);

        addActionMessageToVO(UserListVO, locale, messageKey, null);

        return returnListToUser(UserListVO);
    }

    private UserListVO addActionMessageToVO(UserListVO UserListVO, Locale locale, String actionMessageKey, Object[] args) {
        if (StringUtils.isEmpty(actionMessageKey)) {
            return UserListVO;
        }

        UserListVO.setActionMessage(messageSource.getMessage(actionMessageKey, args, null, locale));

        return UserListVO;
    }

}

服务已存在:

@Service("userService")
@Transactional
public class UserService {
     @Autowired
     private UserRepository userRepository;

     @Transactional(readOnly = true)
        public UserListVO findAll(int page, int maxResults) {
            Page<User> result = executeQueryFindAll(page, maxResults);

            if(shouldExecuteSameQueryInLastPage(page, result)){
                int lastPage = result.getTotalPages() - 1;
                result = executeQueryFindAll(lastPage, maxResults);
            }

            return buildResult(result);
        }

     private Page<User> executeQueryFindAll(int page, int maxResults) {
            final PageRequest pageRequest = new PageRequest(page, maxResults, sortByNameASC());
            System.out.println("Now in ExectueQuery"+pageRequest);
            return userRepository.findAll(pageRequest);
     }
     private Sort sortByNameASC() {
            return new Sort(Sort.Direction.ASC, "name");
     }
     private UserListVO buildResult(Page<User> result) {
            return new UserListVO(result.getTotalPages(), result.getTotalElements(), result.getContent());
     }

     private boolean shouldExecuteSameQueryInLastPage(int page, Page<User> result) {
            return isUserAfterOrOnLastPage(page, result) && hasDataInDataBase(result);
     }
     private boolean isUserAfterOrOnLastPage(int page, Page<User> result) {
            return page >= result.getTotalPages() - 1;
     }

     private boolean hasDataInDataBase(Page<User> result) {
        return result.getTotalElements() > 0;
     }

}

我添加了存储库

@Repository("userRepository")
public interface UserRepository extends JpaRepository<User, Integer> {
    Page<User> findByUserNameLike(Pageable pageable, String UserName);

}

WebConfiguration

@Configuration
@EnableWebMvc
@ComponentScan(basePackages="com.sesame")
@EnableAutoConfiguration
@PropertySource(value = { "classpath:application.properties" })
@EnableScheduling 
@EnableAspectJAutoProxy 
@EnableCaching
public class WebConfig extends WebMvcConfigurerAdapter {

    @Autowired 
    private Environment env;
    @Bean
    public MessageSource messageSource() {
        ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
        messageSource.setBasename("messages");
        return messageSource;
    }

    @Bean
    public LocaleResolver localeResolver() {
        SessionLocaleResolver resolver = new SessionLocaleResolver();
        resolver.setDefaultLocale(Locale.ENGLISH);
        return resolver;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        LocaleChangeInterceptor changeInterceptor = new LocaleChangeInterceptor();
        changeInterceptor.setParamName("language");
        registry.addInterceptor(changeInterceptor);
    }

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




    @Bean public static PropertySourcesPlaceholderConfigurer placeHolderConfigurer() { 
        return new PropertySourcesPlaceholderConfigurer(); 
    }


    @Bean
    public JavaMailSenderImpl javaMailSenderImpl() {
    JavaMailSenderImpl mailSenderImpl = new JavaMailSenderImpl();
    mailSenderImpl.setHost(env.getProperty("smtp.host"));
    mailSenderImpl.setPort(env.getProperty("smtp.port", Integer.class));
    mailSenderImpl.setProtocol(env.getProperty("smtp.protocol"));
    mailSenderImpl.setUsername(env.getProperty("smtp.username"));
    mailSenderImpl.setPassword(env.getProperty("smtp.password"));

    Properties javaMailProps = new Properties();
    javaMailProps.put("mail.smtp.auth", true);
    javaMailProps.put("mail.smtp.starttls.enable", true);

    mailSenderImpl.setJavaMailProperties(javaMailProps);

    return mailSenderImpl;
    }

    @Bean public CacheManager cacheManager() { 

        return new ConcurrentMapCacheManager(); 

    }





    @Bean
    public ServletRegistrationBean dispatcherRegistration() {

        ServletRegistrationBean registration = new ServletRegistrationBean(
                dispatcherServlet());
        registration.addUrlMappings("/");
        registration.addUrlMappings("*.pdf");
        registration.addUrlMappings("*.json");
        registration.addUrlMappings("*.js");
        registration.addUrlMappings("*.xml");
        registration.addUrlMappings("*.css");
        return registration;
    }

    @Bean(name = DispatcherServletAutoConfiguration.DEFAULT_DISPATCHER_SERVLET_BEAN_NAME)
    public DispatcherServlet dispatcherServlet() {
        return new DispatcherServlet();
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resources/pdfs/**").addResourceLocations(
                "/WEB-INF/pdf/");
        registry.addResourceHandler("/resources/js/**").addResourceLocations(
                "/WEB-INF/resources/js/");
        registry.addResourceHandler("/resources/css/**").addResourceLocations(
                "/WEB-INF/resources/css/");
        registry.addResourceHandler("/resources/img/**").addResourceLocations(
                "/WEB-INF/resources/img/");
    }

    @Bean
    public  ViewResolver tilesViewResolver() {
        return new TilesViewResolver();
    }

    @Bean
    public TilesConfigurer tilesConfigurer() {

        TilesConfigurer tiles = new TilesConfigurer();
        tiles.setDefinitions(new String[] {"/WEB-INF/tiles.xml"});
        tiles.setCheckRefresh(true);
        return tiles;
    }




}

1 个答案:

答案 0 :(得分:0)

创建JPA配置类,如下所示:

@Configuration
@EnableJpaRepositories(basePackages="com.sesame.repository")
@EntityScan(basePackages="com.sesame.model")
public class JpaConfiguration  {

}