S
S
sanek_gyy2019-04-16 17:03:43
Java
sanek_gyy, 2019-04-16 17:03:43

How to fix NPE of service in ConstraintValidator?

I create an annotation for validation

import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.*;

@Target({ElementType.TYPE, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = {OperandTypeComparisonValidator.class})
@Documented
public @interface ValidOperandTypeComparison {
    String message() default "com.validation.ValidPatternRows.message";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};
}

and implementation
public class OperandTypeComparisonValidator implements ConstraintValidator<ValidOperandTypeComparison, Pattern> {
    
    @Autowired
    private EventDefinitionService eventDefinitionService;
    
    @Override
    public void initialize(ValidOperandTypeComparison constraintAnnotation) {
    }

    @Override
    public boolean isValid(Pattern pattern, ConstraintValidatorContext constraintValidatorContext) {
        SequentialPattern sequentialPattern = (SequentialPattern) pattern;

        List<SequentialPatternRow> rows = sequentialPattern.getRows();

        SequentialPatternRow row1 = rows.get(1);
        BinaryExpression expression1 = (BinaryExpression) row1.getNewConditions();
        Rule rule1 = row1.getRule();
        String eventId1 = rule1.getEventDefinitionId();

        EventDefinition eventDefinition1 = eventDefinitionService.get(eventId1);

and configuration in Application
@SpringBootApplication
@EnableSwagger2
@EnableDiscoveryClient
@EnableScheduling
public class Application {

    @Autowired
    private Environment env;

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Bean
    public LocalValidatorFactoryBean validatorFactory() {
        LocalValidatorFactoryBean factoryBean = new LocalValidatorFactoryBean();
        factoryBean.setProviderClass(HibernateValidator.class);
        factoryBean.setValidationMessageSource(messageSource());
        factoryBean.afterPropertiesSet();
        return factoryBean;
    }

It is not possible to make an Autowired service. How to do it?
Debugger example
5cb5e4a0d1290421258908.png

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question