2017-04-26 43 views
0

我有一个Spring Boot应用程序,我添加了一些我在常规Spring MVC应用程序(不是Boot)中创建的代码。为公共接口添加Bean

当我运行它,我得到一个错误:

*************************** 
APPLICATION FAILED TO START 
*************************** 

Description: 

Field userService in app.WelcomeController required a bean of type 'com.myorg.account.service.UserService' that could not be found. 


Action: 

Consider defining a bean of type 'com.myorg.account.service.UserService' in your configuration. 

所以我加入资格,并自动装配Autowired到UserService。下面的完整代码。

package com.myorg.account.service; 

import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.beans.factory.annotation.Qualifier; 
import org.springframework.context.annotation.Bean; 
import org.springframework.context.annotation.Configuration; 
import org.springframework.stereotype.Controller; 
import com.myorg.account.model.User; 

@Controller 
@Configuration 
public interface UserService { 
    @Autowired(required = true) 
    @Qualifier(value="UserService") 
    @Bean 
    void save(User user); 

    User findByUsername(String username); 
} 

WelcomeController上面我指定了我认为可以解决问题的限定符。

@ComponentScan 
@Controller 
@Service("UserInterface") 
public class WelcomeController { 

这里是错误中提到的userService字段。这是来自WelcomeController.java

@RequestMapping(value = "/registration", method = RequestMethod.POST) 
    public String registration(@ModelAttribute("userForm") User userForm, BindingResult bindingResult, Model model) { 
     userValidator.validate(userForm, bindingResult); 

     if (bindingResult.hasErrors()) { 
      return "registration"; 
     } 

     userService.save(userForm); 

     securityService.autologin(userForm.getUsername(), userForm.getPasswordConfirm()); 

     return "redirect:/welcome"; 
    } 

在此先感谢。

+0

我不知道这将如何工作。我看到您的代码存在多个问题。在网上寻找一个可行的例子,可以让你知道如何把事情放在一起。 –

+0

有什么特别的你会指向我? – InTheShell

回答

2

您应该将@Controller注释不添加到接口UserService,而是添加到实现UserService接口的类。

UserService删除所有注释,仅在@Controller左“WelcomeController”

@Controller 
public class WelcomeController implements UserService { 
+0

嗨亚历山大,谢谢你的回答。我尝试将@Controller添加到UserServiceImplementation,并且该应用程序尚未运行。还有什么我可能需要做的,像其他注释一样? – InTheShell

+1

你需要这样做,我在我的答案中写道,并用'@ Configuration'和'@ ComponentScan'为应用程序配置创建新类。 –

+0

谢谢,这解决了我的问题。你让我很开心! – InTheShell