Skip to content

sunilsoni/annotation-learning

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

26 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Annotations:

  • @JsonProperty The @JsonProperty annotation is used to map property names with JSON keys during serialization and deserialization. By default, if you try to serialize a POJO, the generated JSON will have keys mapped to the fields of the POJO. If you want to override this behavior, you can use the @JsonProperty annotation on the fields. It takes a String attribute that specifies the name that should be mapped to the field during serialization.

You can also use this annotation during deserialization when the property names of the JSON and the field names of the Java object do not match.

  • @JsonIgnore Simple annotation to use for ignoring specified properties: Only needs to be added to one of accessors/mutators (field, getter/setter, constructor parameter), but will have effect on the "whole" property: that is, adding annotation to a "getter" will also disable "setter" unless "setter" has @JsonProperty, in which case this is considered a "split property" with enabled "setter" but no "getter" ("read-only", so that property may be read from input, but is not written output)

  • @JsonAlias Annotation that can be used to define one or more alternative names for a property, accepted during deserialization as alternative to the official name. Alias information is also exposed during POJO introspection, but has no effect during serialization where primary name is always used.

    Example
 public class Info {
   @JsonAlias({ "n", "Name" })
   public String name;
 }
  • @JsonCreator Marker annotation that can be used to define constructors and factory methods as one to use for instantiating new instances of the associated class.

    NOTE

    When annotating creator methods (constructors, factory methods), method must either be:

Single-argument constructor/factory method without JsonProperty annotation for the argument: if so, this is so-called "delegate creator", in which case Jackson first binds JSON into type of the argument, and then calls creator. This is often used in conjunction with JsonValue (used for serialization).

Constructor/factory method where every argument is annotated with either JsonProperty or JacksonInject, to indicate name of property to bind to

Also note that all JsonProperty annotations must specify actual name (NOT empty String for "default") unless you use one of extension modules that can detect parameter name; this because default JDK versions before 8 have not been able to store and/or retrieve parameter names from bytecode. But with JDK 8 (or using helper libraries such as Paranamer, or other JVM languages like Scala or Kotlin), specifying name is optional. One common use case is to use a delegating Creator to construct instances from scalar values (like java.lang.String) during deserialization, and serialize values using JsonValue.

NOTE

As of Jackson 2.6, use of JsonProperty.required() is supported for Creator methods (but not necessarily for regular setters or fields!).

Def 2

The Jackson annotation @JsonCreator is used to tell Jackson that the Java object has a constructor (a "creator") which can match the fields of a JSON object to the fields of the Java object.

The @JsonCreator annotation is useful in situations where the @JsonSetter annotation cannot be used. For instance, immutable objects do not have any setter methods, so they need their initial values injected into the constructor. Look at this PersonImmutable class as example:

public class PersonImmutable {

    private long   id   = 0;
    private String name = null;

    public PersonImmutable(long id, String name) {
        this.id = id;
        this.name = name;
    }
    public long getId() {
        return id;
    }
    public String getName() {
        return name;
    }
}

To tell Jackson that it should call the constructor of PersonImmutable we must add the @JsonCreator annotation to the constructor. But that alone is not enough. We must also annotate the parameters of the constructor to tell Jackson which fields from the JSON object to pass to which constructor parameters. Here is how the PersonImmutable class looks with the @JsonCreator and @JsonProperty annotations added:

public class PersonImmutable {

    private long   id   = 0;
    private String name = null;

     @JsonCreator
        public PersonImmutable(
                @JsonProperty("id")  long id,
                @JsonProperty("name") String name  ) {

            this.id = id;
            this.name = name;
        }
    public long getId() {
        return id;
    }
    public String getName() {
        return name;
    }
}

Notice the annotation above the constructor and the annotations before the constructor parameters. Now Jackson is capable of creating a PersonImmutable from this JSON object:

{
  "id"   : 1234,
  "name" : "John"
}
Def 3

The @JsonCreator annotation is used to tune the constructor/factory used in deserialization. It’s very helpful when we need to deserialize some JSON that doesn’t exactly match the target entity we need to get.

Let’s look at an example; say we need to deserialize the following JSON:

{
    "id":1,
    "theName":"My bean"
}

However, there is no theName field in our target entity – there is only a name field. Now – we don’t want to change the entity itself – we just need a little more control over the unmarshalling process – by annotating the constructor with @JsonCreator and using the @JsonProperty annotation as well:

public class BeanWithCreator {
    public int id;
    public String name;

    @JsonCreator
    public BeanWithCreator(
      @JsonProperty("id") int id,
      @JsonProperty("theName") String name) {
        this.id = id;
        this.name = name;
    }
}
  • @Component, @Repository, @Service, @ControllerThis annotation is used on classes to indicate a Spring component. The @Component annotation marks the Java class as a bean or say component so that the component-scanning mechanism of Spring can add into the application context.

@Component annotation is the more generalized form that are considered as candidates for auto-detection when using annotation-based configuration and classpath scanning. This annotation extended to more specific forms such as @Controller, @Repository and @Service.

@Repository

The @Repository annotation is a specialization of the @Component annotation with similar use and functionality. In addition to importing the DAOs into the DI container, it also makes the unchecked exceptions (thrown from DAO methods) eligible for translation into Spring DataAccessException.

@Service

The @Service annotation is also a specialization of the component annotation. It doesn’t currently provide any additional behavior over the @Component annotation, but it’s a good idea to use @Service over @Component in service-layer classes because it specifies intent better. Additionally, tool support and additional behavior might rely on it in the future.

@Controller

@Controller annotation marks a class as a Spring Web MVC controller. It too is a @Component specialization, so beans marked with it are automatically imported into the DI container. When you add the @Controller annotation to a class, you can use another annotation i.e. @RequestMapping; to map URLs to instance methods of a class.

Inner Static Component

We can also define a static inner class as a component. Default bean name of the inner static class would be decapitalized name of the outer class + “.” + Inner class name. For example, to get the bean of inner static class EmployeeServiceImpl.EmployeeInnerBean, it would be:

 context.getBean("employeeServiceImpl.EmployeeInnerBean");
  • @Configuration @Configuration classes are just like regular @Components classes as @Configuration is meta-annotated with @Component.

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Configuration {
	@AliasFor(annotation = Component.class)
	String value() default "";
}

When the class containing @Configuration or @Component contains @Bean annotated methods, those methods act as factory beans so what is the difference? The difference lies in the inter-bean references when one @Bean method invokes another @Bean method. If the class is annotated with @Component the @Bean method invocation is treated as a standard Java method invocation whereas when a @Bean method declared in @Configuration is called the method invocation is intercepted using CGLIB proxy and the bean cached in the spring container is returned.

When a @Bean annotated method owned by the @Component class is called the method is simply re-invoked and we will get a new bean at each invocation rather than returning the one cached in the container. When @Bean methods are re-invoked @Configuration annotation is preferred.

Releases

No releases published

Packages

No packages published

Languages