Is there any particulars on when to use the annotations in java, or to put it more precisely, is the answer to the following question Yes or No
Only under this condition, can this particular annotations be used.
Obviously, the this in the above statement can be anything or nothing.
The reason I ask this question is that I was given this code base and in their they had used some annotations to validate the classes, properties etc. Now, this is a web application and it makes use of all the spring beans and what not.
I tried the following code. (This is just normal java code, no spring or anything.This is the entire code)
public class AnnotationsTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
TestMe t = new TestMe();
System.out.println(t.getTest1());
}
}
class TestMe{
@NotNull
private String test1;
public String getTest1() {
return test1;
}
public void setTest1(String test1) {
this.test1 = test1;
}
}
This one prints out null as output. Why is not any validation happening?
Well, what I am guessing is that I've provided the annotations for this, but have not really validated. So I went to this link. Therein he had all sorts of ValidationFactory
and what not.
So I wrote,
public class AnnotationsTest{
private static Validator validator;
public static void main(String[] args) {
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
validator = factory.getValidator();
TestMe t = new TestMe();
Set<ConstraintViolation<TestMe>> constraintViolations =
validator.validate(t);
assertEquals(1, constraintViolations.size());
assertEquals("may not be null", constraintViolations.iterator().next().getMessage());
}
}
But this one give the following error
Exception in thread "main" javax.validation.ValidationException: Unable to find a default provider
at javax.validation.Validation$GenericBootstrapImpl.configure(Validation.java:264)
at javax.validation.Validation.buildDefaultValidatorFactory(Validation.java:111)
at AnnotationsTest.main(AnnotationsTest.java:29)
So here's my questions:
1. What exactly happened in the two cases above?
2. I thought that annotations were enough, as in Autowired
and stuff, they would just inject the classes on it's own. But here why do I need to do the extra stuff to validate. Why doesnt @NotNull
validates the things on it's own.
Thanks.