Spring validator constructor

 
 
 
Сообщения:10
Проблема: Перенес валидацию RegisterUserDto из контроллера в сервис. Теперь, при использовании xml конфигурации, не инициализируется UniqueValidator, spring не может найти конструктор с параметром (до этого использовался autowiring и было все ok).

Caused by: org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [org.jtalks.jcommune.model.validation.validators.UniqueValidator]: No default constructor found; nested exception is java.lang.NoSuchMethodException: org.jtalks.jcommune.model.validation.validators.UniqueValidator.<init>()
	at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:83)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1006)
	... 126 more
Caused by: java.lang.NoSuchMethodException: org.jtalks.jcommune.model.validation.validators.UniqueValidator.<init>()
	at java.lang.Class.getConstructor0(Class.java:2730)
	at java.lang.Class.getDeclaredConstructor(Class.java:2004)
	at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:78)
	... 127 more


При использовании конструктора по умолчанию и сеттера, ValidatorDao равен null (не инициализируется). Такое ощущение, что для разрешения зависимостей в валидаторах spring может использовать только autowiring.

public class UniqueValidator implements ConstraintValidator<Unique, String> {

    private Class<? extends Entity> entity;
    private String field;
    private boolean ignoreCase;

    private ValidatorDao<String> dao;

    /**
     * @param dao to perform database-based validations
     */
    //@Autowired
    public UniqueValidator(ValidatorDao<String> dao) {
        this.dao = dao;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void initialize(Unique annotation) {
        this.entity = annotation.entity();
        this.field = annotation.field();
        this.ignoreCase = annotation.ignoreCase();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        // null value should be processed by other constraint validators
        return value == null || dao.isResultSetEmpty(entity, field, value, ignoreCase);
    }
}


public class TransactionalAuthenticator extends AbstractTransactionalEntityService<JCUser, UserDao>
        implements Authenticator {

    private PluginLoader pluginLoader;
    private EncryptionService encryptionService;
    private AuthenticationManager authenticationManager;
    private SecurityContextHolderFacade securityFacade;
    private RememberMeServices rememberMeServices;
    private SessionAuthenticationStrategy sessionStrategy;
    //@Autowired
    private Validator validator;

    private static final Logger LOGGER = LoggerFactory.getLogger(TransactionalAuthenticator.class);

    public TransactionalAuthenticator(PluginLoader pluginLoader, UserDao dao,
                                      EncryptionService encryptionService,
                                      AuthenticationManager authenticationManager,
                                      SecurityContextHolderFacade securityFacade,
                                      RememberMeServices rememberMeServices,
                                      SessionAuthenticationStrategy sessionStrategy,
                                      Validator validator) {
        super(dao);
        this.pluginLoader = pluginLoader;
        this.encryptionService = encryptionService;
        this.authenticationManager = authenticationManager;
        this.securityFacade = securityFacade;
        this.rememberMeServices = rememberMeServices;
        this.sessionStrategy = sessionStrategy;
        this.validator = validator;
    }

    public BindingResult register(RegisterUserDto registerUserDto)
            throws UnexpectedErrorException, NoConnectionException {
        BindingResult result = new BeanPropertyBindingResult(registerUserDto, "newUser");
        BindingResult jcErrors = new BeanPropertyBindingResult(registerUserDto, "newUser");
        validator.validate(registerUserDto, jcErrors);
        registerByPlugin(registerUserDto.getUserDto(), true, result);
        mergeValidationErrors(jcErrors, result);
        if(!result.hasErrors()) {
            registerByPlugin(registerUserDto.getUserDto(), false, result);
        }
        return result;
    }
}

applicationContext-dao.xml
  <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"/>
  <bean class="org.springframework.validation.beanvalidation.MethodValidationPostProcessor">
    <property name="validator" ref="validator"/>
  </bean>
  <bean class="org.springframework.validation.beanvalidation.BeanValidationPostProcessor">
    <property name="validator" ref="validator"/>
  </bean>

  <bean id="validatorDAO"
        class="org.jtalks.jcommune.model.dao.hibernate.ValidatorHibernateDao">
    <constructor-arg ref="sessionFactory"/>
  </bean>

  <bean id="uniqueValidator" class="org.jtalks.jcommune.model.validation.validators.UniqueValidator">
    <constructor-arg ref="validatorDAO"/>
  </bean>


Подскажите, пожалуйста, если кто сталкивался с похожим, то как решили?
 
Модераторы:katctapobepІраїдаJulia AtlyginaJulik21Julikdsafjifb
Сейчас эту тему просматривают:Нет