I know it's a possible duplicate and I found several threads like How can I find all beans with the custom annotation @Foo? or Custom annotation is not working on spring Beans but that's not really what I do or want to do.
I want an easy validator for the length of attributes of a class. Dont tell me about @Length
or @Size
. They're not helpful here. I tried several solutions and none of them did work.
CustomAnnotation:
@Target({ ElementType.METHOD, ElementType.FIELD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = CheckLengthValidator.class)
@Qualifier // got this one from a solution
public @interface CheckLength {
Class<?> className();
Class<?>[] groups() default {};
String message() default "List is not valid";
Class<? extends Payload>[] payload() default {};
}
CustomAnnotationValidator (methods not implemented yet):
public class CheckLengthValidator implements ConstraintValidator<CheckLength, List<Transaction>> {
@Override
public void initialize(CheckLength a) {
//get values which are defined in the annotation
System.out.println("init");
test = a.message();
}
@Override
public boolean isValid(List<Transaction> value, ConstraintValidatorContext context) {
for (Transaction x : value) {
if (x.getTimestamp().length() > 30) {
System.out.println("not valid");
return false;
}
}
return true;
}
}
So where do I use it? At my API where all autowired repos are.
@CrossOrigin(origins = "http://localhost:4200")
@RestController
public class FileManagementRestAPI {
@Autowired
@CheckLength(className = Transaction.class)
List<Transaction> transaction = new ArrayList<>();
...
}
Later this will be called to fill the list.
transaction.addAll((Collection<? extends Transaction>) csvToBean.parse());
What I tried:
I read about a solution which I later found out it is deprecated or not working anymore with CommandLineRunner
and AnnotationConfigApplicationContext
.
Then I've read that I have to declare it as Bean but a List here isn't a Bean or do I still need to do something with Beans? Saw something like this but didn't know what to do with it then:
public class InitBeans implements BeanPostProcessor { ... }
The error I get now:
Field transaction in com.stuff.project.apis.FileManagementRestAPI required a bean of type 'java.util.List' that could not be found.
The injection point has the following annotations:
- @org.springframework.beans.factory.annotation.Autowired(required=true)
- @com.stuff.project.utils.CheckLength(message=List is not valid, groups=[], payload=[], className=class com.stuff.project.entity.Transaction)
Action:
Consider defining a bean of type 'java.util.List' in your configuration.
There were several other errors when I was trying to get it running.