Код: Выделить всё
package com.example.demo;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.context.annotation.Configuration;
@Configuration
class ConfigLoader implements BeanDefinitionRegistryPostProcessor {
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry)
throws BeansException {
registry.registerBeanDefinition("fooBarProperties",
BeanDefinitionBuilder
.genericBeanDefinition(FooBarProperties.class)
.addPropertyValue("foo", "bar")
.addPropertyValue("bar", "")
.getBeanDefinition());
}
}
Код: Выделить всё
package com.example.demo;
import jakarta.validation.constraints.NotBlank;
import lombok.Getter;
import lombok.Setter;
import org.springframework.validation.annotation.Validated;
@Getter
@Setter
@Validated
public class FooBarProperties {
@NotBlank
private String foo;
@NotBlank
private String bar;
}
Код: Выделить всё
@Component
public class HelloWorldComponent {
public HelloWorldComponent(FooBarProperties fooBarProperties) {
System.out.printf("foo is '%s', bar is '%s'%n", fooBarProperties.getFoo(),
fooBarProperties.getBar());
// foo is 'bar', bar is ''
}
}
< /code>
Я также был бы в порядке с вручную проверкой свойств. Однако, если я попытаюсь сделать это, валидатор считает, что все поля являются null Код: Выделить всё
@Component
public class HelloWorldComponent {
public HelloWorldComponent(SmartValidator validator, FooBarProperties fooBarProperties) {
System.out.printf("foo is '%s', bar is '%s'%n", fooBarProperties.getFoo(),
fooBarProperties.getBar());
// foo is 'bar', bar is ''
var errors = new BeanPropertyBindingResult(fooBarProperties, "FooBarProperties");
validator.validate(fooBarProperties, errors);
for (var error : errors.getFieldErrors()) {
System.out.println(error.getField() + ": " + error.getDefaultMessage());
}
// foo: must not be blank
// bar: must not be blank
}
}
Учитывая все это, есть ли способ подтвердить Foobarperties с их валидацией Jakarta?>
Подробнее здесь: https://stackoverflow.com/questions/794 ... tprocessor