These annotations are used to stereotype classes with regard to the application tier that they belong to. Classes that are annotated with one of these annotations will automatically be registered in the Spring application context if <context:component-scan> is in the Spring XML configuration(spring.xml).
+------------+-----------------------------------------------------+
| Annotation | Meaning | +------------+-----------------------------------------------------+ | @Component | generic stereotype for any Spring-managed component | | @Repository| stereotype for persistence layer | | @Service | stereotype for service layer | | @Controller| stereotype for presentation layer (spring-mvc) |
+------------+-----------------------------------------------------+
@Component public class Circle { private Point center; ---- }
@Repository public class CircleDaoImpl implements CircleDao { private Point center; ---- }
@Service public class CircleServiceImpl implements CircleService { private Point center; ---- }
@Controller public class CircleController { private Point center; ---- }
Enable component scanning
Spring by default does not scan means Spring container does create bean for those classes whose annotated with above for stereotype annotations. So we have to enable component scanning explicity by using “context:component-scan” tag in your applicationContext.xml file. So stereotype annotations will be scanned and configured only when they are scanned by DI container of spring framework.
<context:component-scan base-package="com.dineshonjava.app.service" /> <context:component-scan base-package="com.dineshonjava.app.dao" /> <context:component-scan base-package="com.dineshonjava.app.controller" />
The context:component-scan element requires a base-package attribute, the value of base-package attribute should specifies a starting point for a recursive component search. Spring recommends do not use your top package for scanning, so you should declare specific component-scan elements.
Note: If you are using component-scan property for context namespace then you no longer need to declare context:annotation-config, because autowiring is implicitly enabled when component scanning is enabled.
Where to use stereotype annotations?
Always use these annotations over concrete classes; not over interfaces.
Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…
Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…
Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…
Technology has emerged a lot in the last decade, and now we have artificial intelligence;…
Managing a database is becoming increasingly complex now due to the vast amount of data…
Overview In this article, we will explore Spring Scheduler how we could use it by…