@Required Annotation Example in Spring



The @Required annotation applies to bean property setter methods, as in the following example:

    public class SimpleMovieLister {
         private MovieFinder movieFinder;
        @Required
       public void setMovieFinder(MovieFinder movieFinder) {
            this.movieFinder = movieFinder;
       }
   }


This annotation simply indicates that the affected bean property must be populated at configuration time: either through an explicit property value in a bean definition or through autowiring. The container will throw an exception if the affected bean property has not been populated; this allows for eager and explicit failure, avoiding NullPointerExceptions or the like later on. Note that it is still recommended to put assertions intothe bean class itself (for example into an init method) in order to enforce those required references and values even when using the class outside of a container.

No comments:

Post a Comment