2013-03-08 6 views
0

Я получаю эту ошибку:Autowired весной дает ошибку: Инъекция autowired зависимостей не удалось

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'newStep2Controller': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void projecthealth.web.NewStep2Controller.setUserService(projecthealth.service.UserService); nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [projecthealth.service.UserService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {} 
    org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:288) 
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1120) 
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:522) 

контроллер класса

@Controller 
    @RequestMapping("/newStep2.htm") 
    @SessionAttributes("user") 
    @ComponentScan("projecthealth.service") 
public class NewStep2Controller 
{ 
protected final Log logger = LogFactory.getLog(getClass()); 
private UserService userService; 

@Autowired 
public void setUserService(UserService userService) { 
    this.userService = userService; 
} 
    @RequestMapping(method = RequestMethod.GET) 
public String showUserForm(ModelMap model) 
{ 
    model.addAttribute("user"); 

    return "userForm"; 
} 

обслуживание существующего:

public interface UserService { 

void createUser(User user) throws ServiceException; 

/** 
* 
* @param userId (email is user id) 
* @return 
* @throws ServiceException 
*/ 
User getUserById(String userId) throws ServiceException; 

void deleteUser(String userId) throws ServiceException; 

/** 
* 
* @param newUserObject 
* @param userId (email is user id) 
* @return 
* @throws ServiceException 
*/ 
User updateUser(User newUserObject, String userId) throws ServiceException; 
} 

I 've добавил это к xml

<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/> 

Я добавил UserServiceImpl

public class UserServiceImpl extends BaseServiceImpl<User> implements UserService{ 

public static final String FIELD_EMAIL = "email"; 

public void createUser(User user) throws ServiceException { 
    insert(user); 
} 

public User getUserById(String userId) throws ServiceException { 
    return (User) findOne(User.class, FIELD_EMAIL, userId); 
} 

public void deleteUser(String userId) throws ServiceException { 
    delete(User.class, FIELD_EMAIL, userId); 
} 

public User updateUser(User newUserObject, String oldEmail) throws ServiceException { 
    MongoTemplate template = getTemplate(); 
    User userObject = getUserById(oldEmail); 

    List<DietCategory> dietaryPreferences = newUserObject.getDietaryPreferences(); 

    if(dietaryPreferences != null){ 
     userObject.setDietaryPreferences(dietaryPreferences); 
    } 
    userObject.setEmail(newUserObject.getEmail()); 
    userObject.setFirstname(newUserObject.getFirstname()); 
    userObject.setHeight(newUserObject.getHeight()); 
    userObject.setLastname(newUserObject.getLastname()); 
    userObject.setPassword(newUserObject.getPassword()); 
    userObject.setWeight(newUserObject.getWeight()); 
    template.save(userObject); 
    return newUserObject; 
} 

public List<User> getAllUser() throws ServiceException { 
    return findAll(User.class); 
} 

StackOverflow делает добавить текст, потому что есть слишком много кода в моем посте. , вы можете игнорировать этот комментарий.

+1

А где реализация вашего интерфейса? Spring должен что-то создать, и это не может быть интерфейс. – partlov

ответ

0

Вам необходимо создать компонент UserService в вашем xml.

Или ваш контроллер не может его найти!

2

Было бы лучше, если бы вы предоставили реализацию UserService.

Убедитесь, что реализация аннотируется с помощью @Service.

+0

поэтому выше, где у меня есть UserSerivceImpl, я должен включить @Service над строкой «public class UserServiceImpl extends BaseServiceImpl» ?? –

0

Как насчет внедрения вашей службы? Вы аннотировали свой класс UserService и класс реализации UserService с помощью аннотации @Service? Вы также можете пропустить геттер & setter в контроллере и установить @Повторенная аннотация для вашего поля, я знаю, что она работает, но я понятия не имею, как это сделать.

Вы должны также проинструктировать Spring для поиска этих аннотаций в указанных пакетах, это то, как я делаю:

<context:annotation-config/> 
    <context:component-scan base-package="your_package"/> 
    <mvc:annotation-driven/> 
+0

У меня это уже есть в моем xml. –