简体   繁体   中英

What is the difference between Constraints and Annotations?

I've been studying Java EE 6 and I am confused about the difference between Annotations and Constraints. What exactly is the difference between them?

Annotations such as @Deprecated , @WebServlet , @NotNull , etcetera carry metadata with the class. Before annotations exist, this was usually done by XML configuration files. Annotations can be determined with help of Java Reflection.

Constraints are business rules which are to be applied on classes and/or fields (properties) of the class. For example, if the business rule mandates that the user name may never be null, then you'd like to put the @NotNull annotation to define the constraint.

public class User {

    @NotNull
    private String name;

    // ...
}

I see in your question history that you're familiar with JSF, the Java EE supplied web MVC framework. JSF can make use of it to validate the user input.

<h:inputText id="username" value="#{user.name}" />
<h:message for="username" />

When the user leaves the input field blank, a message will be displayed which informs the user that the value may not be null (the exact message itself is customizable).

See also:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM