【问题标题】:Spring dependency injection doesn't work in ConstraintValidatorSpring 依赖注入在 ConstraintValidator 中不起作用
【发布时间】:2018-08-22 18:15:19
【问题描述】:

我正在尝试使用 @Autowired 将我的服务用于自定义 ContextValidator 注释。我在 SOF 上的旧问题中寻找一些帮助,但不幸的是,我创建的是一个新问题。我的目标是有效 bean 的属性,上面有注释 @MyId。

这是我的代码:

@Documented
@Constraint(validatedBy = { MyIdValidator.class })
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
@Retention(RUNTIME)
public @interface MyIdSpring {

    String message() default "Invalid ID!";

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

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

Valdiator 类:

@Configurable(autowire = Autowire.BY_TYPE, dependencyCheck = true)
public class MyIdValidator implements ConstraintValidator<MyId, TestID> {

    @Autowired
    private ITestService testService;

    @Override
    public void initialize(MyId constraintAnnotation) {
    }

    @Override
    public boolean isValid(TestID value, ConstraintValidatorContext context) {

        System.out.println(testService);

        return false;
    }
}

配置:

@Configuration
public class ValidatorConfig {

    @Bean
    public LocalValidatorFactoryBean validator() {
        LocalValidatorFactoryBean bean = new LocalValidatorFactoryBean();
        return bean;
    }
}

服务:

@Service
public class TestService implements ITestService { .. }

ITestService 始终为空。你能帮我修一下吗?我正在使用 Spring Boot 1.5。

【问题讨论】:

  • 请显示您的组件扫描配置,以及每个对象的包
  • @MichaelPeacock 我没有明确定义的扫描,我在根目录中有 SpringBoot 初始化程序,在下面的包中有其他组件,如 /service/TestService、/config/ValidatorConfig、...
  • by SpringBoot Initializer,您是说带有 SpringBootApplication 注解的主类在此 Service 注解类的父包中?

标签: java spring dependency-injection bean-validation


【解决方案1】:

使用 @Qualifier 注释告诉 Spring 你的实现类。

@Autowired
@Qualifier("testService")
private ITestService testService;

【讨论】:

  • 服务仍为空:/
  • 你的@ComponentScan 是否包含TestService 类?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-06-09
  • 1970-01-01
  • 2017-10-01
  • 2021-12-16
  • 1970-01-01
  • 1970-01-01
  • 2018-06-20
相关资源
最近更新 更多