2013-07-11 4 views
3

У меня проблемы с двумя службами, которые я выполнил в классе валидатора. Службы работают нормально, потому что в моем контроллере есть автоукрепление. У меня есть файл applicationContext.xml и файл MyApp-servlet.xml. Мой базовый пакет - es.unican.meteo, и у меня проблемы с пакетом es.unican.meteo.validator. Пакет es.unican.meteo.controller и es.unican.meteo.service могут автоматически обслуживать службы.Проблемы с аннотацией @Autowire (null)

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:context="http://www.springframework.org/schema/context" 
    xmlns:p="http://www.springframework.org/schema/p" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd 
     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd"> 

.... 
some beans 
... 
</beans> 

Myapp-servlet.xml

<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns:context="http://www.springframework.org/schema/context" 
xmlns:mvc="http://www.springframework.org/schema/mvc" 
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd 
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd 
    http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd"> 

    <!-- Enabling Spring beans auto-discovery --> 
    <context:component-scan base-package="es.unican.meteo" /> 

    <!-- Enabling Spring MVC configuration through annotations --> 
    <mvc:annotation-driven /> 

Класс ResetPasswordValidator:

package es.unican.meteo.validator; 


import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.validation.Errors; 
import org.springframework.validation.Validator; 

import es.unican.meteo.model.User; 
import es.unican.meteo.service.MessageService; 
import es.unican.meteo.service.UserService; 

public class ResetPasswordValidation implements Validator{ 

    @Autowired 
    private UserService userService; 

    @Autowired 
    private MessageService messageService; 

    public boolean supports(Class<?> clazz) { 
     return User.class.equals(clazz); 
    } 

    public void validate(Object target, Errors errors) { 
     User user = (User)target; 
     if(userService.getUserByEmail(user.getEmail())==null){ 
      errors.rejectValue("email", messageService.getMessage("app.error.nonexistentemail")); 
     } 
    } 
} 

я могу видеть, контроллеры, услуги и autowired элементы в пружинные элементы , Похоже, что пружина не обнаруживает свойства автоувеличивания в валидаторе пакетов. Есть идеи?

Edit: Протоколирование (полей Autowire) ResetPasswordValidation

12:48:50,697 DEBUG main support.DefaultListableBeanFactory:217 - Creating shared instance of singleton bean 'resetPasswordValidation' 
12:48:50,697 DEBUG main support.DefaultListableBeanFactory:430 - Creating instance of bean 'resetPasswordValidation' 
12:48:50,701 DEBUG main annotation.InjectionMetadata:60 - Found injected element on class [es.unican.meteo.validator.ResetPasswordValidation]: AutowiredFieldElement for private es.unican.meteo.service.UserService es.unican.meteo.validator.ResetPasswordValidation.userService 
12:48:50,702 DEBUG main annotation.InjectionMetadata:60 - Found injected element on class [es.unican.meteo.validator.ResetPasswordValidation]: AutowiredFieldElement for private es.unican.meteo.service.MessageService es.unican.meteo.validator.ResetPasswordValidation.messageService 
12:48:50,702 DEBUG main support.DefaultListableBeanFactory:504 - Eagerly caching bean 'resetPasswordValidation' to allow for resolving potential circular references 
12:48:50,707 DEBUG main annotation.InjectionMetadata:85 - Processing injected method of bean 'resetPasswordValidation': AutowiredFieldElement for private es.unican.meteo.service.UserService es.unican.meteo.validator.ResetPasswordValidation.userService 

ответ

3

Убедитесь, что вы аннотировать класс так, чтобы Spring поднимает его в качестве компонента. Автообслуживание может происходить только в фазах/классах, управляемых контейнером DI.

Добавление @Component приведет к тому, что класс будет подхвачен сканированием компонентов Spring, в результате чего ResetPasswordValidation станет bean-компонентом. На этом этапе он должен иметь право иметь поля автоматически.

+0

@mannuk Помогает ли это? При удаче? –

+0

Ваш вопрос очень интересный @ Кевин. Теперь проект eclipse обнаруживает, что у меня есть автоувеличиваемые элементы в классе проверки, но он не вводит службы. Свойства по-прежнему недействительны, возможно, мне нужно больше вещей? – mannuk

+0

@mannuk Вы аннулировали свои услуги с помощью @Service? –

Смежные вопросы