我无法在自定义验证程序中注入实体存储库。 我对java,spring和jHipster都很陌生,所以我在类似问题的答案中有点迷失。
我有什么:
实体:
@Entity
@Table(name = "building_floor",uniqueConstraints = @UniqueConstraint(name="buildingFloor",columnNames = {"building_id","name"}))
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
@BuildingFloorUnicityValidator
public class BuildingFloor implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotNull
@Size(max = 32)
@Column(name = "name", length = 32, nullable = false)
private String name;
@ManyToOne
@NotNull
private Building building;
//...
自定义注释:
@Documented
@Constraint(validatedBy = BuildingFloorUnicityValidatorCheck.class)
@Target({ ElementType.TYPE, ANNOTATION_TYPE })
@Retention(RUNTIME)
public @interface BuildingFloorUnicityValidator {
String message() default "{builindg floor already exists}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
String value() default "";
}
验证员:
public class BuildingFloorUnicityValidatorCheck implements ConstraintValidator<BuildingFloorUnicityValidator, BuildingFloor> {
@Autowired
private BuildingFloorRepository buildingFloorRepository;
@Override
public void initialize(BuildingFloorUnicityValidator constraintAnnotation) {
}
@Override
public boolean isValid(BuildingFloor value, ConstraintValidatorContext context) {
BuildingFloor existingBuilindg = buildingFloorRepository.findOneByBuildingAndName(value.getBuilding(),value.getName());
return existingBuilindg == null;
}
}
并在我的控制器中:
@PostMapping("/building-floors")
@Timed
public ResponseEntity<BuildingFloorDTO> createBuildingFloor(@Valid @RequestBody BuildingFloorDTO buildingFloorDTO)
因此,当我启动测试时,验证器中的存储库会抛出NullPointerException
Caused by: java.lang.NullPointerException: null
at eu.***.master_data.validator.unicity.BuildingFloorUnicityValidatorCheck.isValid(BuildingFloorUnicityValidatorCheck.java:31)
我错过了什么?
答案 0 :(得分:0)
@Autowired
,因为BuildingFloorUnicityValidatorCheck
不是弹簧bean,您必须使用@Service
或@Component
对其进行注释,或者从@Configuration
实例化它注释类。
顺便说一句,JHipster和Spring更喜欢构造函数注入场注入(你使用的是什么)。 JHipster中的所有服务都使用这种方式,因此您可以在项目中找到许多示例。