Core Spring Annotations – Stereotyping Annotations

Core Spring Annotations – Stereotyping Annotations. Stereotyping Annotations are used to stereotype classes. And these classes are annotated with one of the following annotations, which is registered automatically in the Context of Spring Application.

AnnotationUseDescription
@ComponentTypeThis one is the Generic stereotype annotation for any Spring-managed component.
@ControllerTypeUses stereotypes component, as a Spring MVC (model-view-controller) controller.
@RepositoryTypeThis uses, Stereotype component as a repository. It can be also used to indicates that, those SQLExceptions thrown from the component’s methods should be translated into Spring DataAccessExceptions form.
@ServiceTypeUses, Stereotypes component as a service.

Configuring Beans Automatically

It is possible to automatically registering beans int the Spring. For this, first of all annotate the bean with any of the stereotype annotations. For example:

@Component
public class Traveller {
private String name;
private WorldMap worldmap;
public Pirate(String name) { this.name = name; }
@Autowired
public void setTreasureMap(WorldMap worldMap) {
this.worldMap= worldMap;
}
}

Then add <context:component-scan> to your Spring XML configuration:

<context:component-scan
base-package="com.preprogrammer.traveller" />

The above annotation will tell the Spring to scan com.preprogrammer.traveller, including its subpackages. And will do the bean automatic registration.

Also, you can specify the bean by passing its value, as follows

@Component("Columbus")
public class Traveller { ... }

Specifying Scope For Auto-Configured Beans

By default, all beans are scoped as singleton. But, if you want, you can specify the scope using the @Scope annotation. For example:

@Component
@Scope("prototype")
public class Traveller{ ... }

How to Create Custom Stereotype

Step 1:

@Component public @interface MyComponent { String value() default ""; }

Or Add a filter to to scan for annotations that it normally would not:

Step 2: You the newly created component (MyComponent) as follows in the code:

@MyComponent public class Pirate {...}

Thanks for reading “Core Spring Annotations – Stereotyping Annotations”. I hpe you like it.