Проверка динамических весенних бобов, генерируемых BeandefinitionRegistryPostProcessorJAVA

Программисты JAVA общаются здесь
Anonymous
Проверка динамических весенних бобов, генерируемых BeandefinitionRegistryPostProcessor

Сообщение Anonymous »

У меня есть класс, который реализует Spring BeandefinitionRegistryPostProcessor :

Код: Выделить всё

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());
}
}
Это (динамически) регистрирует бобы класса foobarproperties , который определяется как:

Код: Выделить всё

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;
}
В фактическом приложении может быть несколько FoobarProperties , и фактические значения заполняются из внешней конфигурации. Я хотел бы убедиться, что эти свойства действительны. Учитывая определение ниже, я ожидаю, что Spring вынесет ошибку, потому что значение BAR пустое, в то время как атрибут имеет аннотацию @notblank . Однако этого не происходит: < /p>

Код: Выделить всё

@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 
, вместо того, чтобы поле Bar было пустым:

Код: Выделить всё

@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
}
}
при осмотре бобов, кажется, имеет класс foobarperperties $$ springcglib $$ 0 вместо foobarproperties .
Учитывая все это, есть ли способ подтвердить Foobarperties с их валидацией Jakarta?>

Подробнее здесь: https://stackoverflow.com/questions/794 ... tprocessor

Вернуться в «JAVA»