2017-04-26 54 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