#RequestMapping for #Component Bean - spring

Just a simple question. Does #RequestMapping only works with #Controller classes. I am trying to map a #Component bean in my application using #RequestMapping and its always throwing noHandlerFound No mapping found for HTTP request with URI

Quite right, you can only use #RequestMapping on #Controller annotated classes. From the javadoc of the #Controller class:
Base Controller interface, representing a component that receives HttpServletRequest and HttpServletResponse instances just like a HttpServlet [...]
In addition, the #Controller extends the #Component bean, javadoc:
[#Component] Indicates that an annotated class is a "component". Such classes are considered as candidates for auto-detection when using annotation-based configuration and classpath scanning.
In other words, a #Component (and its sub-annotation #Controller) is what makes a class a Spring bean, but only the #Controller annotation deals with #RequestMapping and other HTTP related operations.
There is more information about stereotype annotations in the Spring reference documentation.

Related

How to Fix Could not autowire. No beans of error in Spring Boot

How can I solve this error. I'm New to Spring-boot
As I can see the spring unable to find the bean UserDetailsServiceImpl, there might be couple of reason for it.
First, you might forgot to put #Service annotation on top of the class UserDetailsServiceImpl. Also, as the context is about Spring security so make sure that this class UserDetailsServiceImpl must implement the interface UserDetailsService
#Service
public class UserDetailsServiceImpl implements UserDetailsService {
}
Second, spring might be unable to scan this folder. So make sure spring IOC must scan this package while intialization and configure the bean.
In order to #Autowired a bean instance, a class should be decorated with Spring stereotype annotation like #Component, #Service, #Repository, #Controller or #Indexed. Just by decorating the class with one of these role annotations, you can use #Autowired to bind with the instance.
Otherwise, if none of these annotations are used, your class instances, you have to manually registered to the BeanFactory like this;
#Configuration
public class SomeClass {
...
#Bean
public UserDetailsServiceImpl userDetailsService() {
return new UserDetailsServiceImpl()
}
}
This answer just talk about your specific question, but you get to find out why #Configuration is used in preceeding example. Define scopes for bindings, singleton (one instance for the application) is the default scope in Spring, you should define scopes for beans if they should be in different scope on your requirements.

Is the Rest Controller class singleton?

I am learning Spring and Spring Boot.
In my Spring boot app, I am using #RestController annotation for one of my classes which receives requests and processes them accordingly.
#RestController
public class SampleController {
......
}
I want to ask would this class annotated with #RestController be a singleton class?
My thought is that this SampleController would also be a bean and since the default scope is Singleton,
it would be a Singleton class. I want to ask whether I am thinking right.
Yes, you are right. Any bean you creating via annotations #Component, #Service, #Repository, #Controller, #RestController and #Bean of course by default have Singleton scope. Check
Bean scope

Can we interchange #Controller and #Service in spring?

Can we interchange #Controller and #Service in spring? I tried and it was working. How are they implemented internally?
#Controller and #Service are special form of #Component. Spring allows you to use it interchangeably, but is it NOT recommended to do it that way. As for instance the #Controller is used on classes to that serves are the Controller on the MVC. Also, spring dispatcher servlet will scan for #RequestMapping on classes which are annotated using #Controller.
#Component
------#Controller
------#Service
------#Repository
#Controller and #Service are ultimately part of #Component. You may interchange them but it is not recommended or follow best practices. The purpose of using 3 different annotation is to we can have separate the layers based on it use more appropriate annotation.
#Controller:
Annotated class indicates that it is a controller component, and mainly used at the presentation layer.
#Controller is used to mark classes as Spring MVC Controller. This annotation is just a specialized version of #Component and it allows the controller classes to be auto-detected based on classpath scanning.
#Service:
It indicates annotated class is a Service component in the business layer.

Using #PropertySouce in #Component

I tried to use #PropertySource in a #Component like:
#Component
#PropertySource("somepropertiesfile.properties")
public class Student {
...
}
It worked fine.
I want to understand, what is the different between using #PropertySource with #Component and #PropertySource with #Configuration.
Is there any difference or impact of using #PropertySource with #Component.
Configuration is itself a Component type, look into the #Configuration annotation implementation below.
#Target(ElementType.TYPE)
#Retention(RetentionPolicy.RUNTIME)
#Documented
#Component
public #interface Configuration {
}
From API
Component: Indicates that an annotated class is a "component". Such classes are considered as candidates for auto-detection when using annotation-based configuration and classpath scanning.
Configuration: Indicates that a class declares one or more #Bean methods and may be processed by the Spring container to generate bean definitions and service requests for those beans at runtime.
The #Bean annotation is used to indicate that a method instantiates, configures and initializes a new object to be managed by the Spring IoC container. These are same as Spring’s XML configuration. You can use #Bean annotated methods with any Spring #Component, however, they are most often used with #Configuration beans.
Here also you can use #PropertySource in #Component class but these are most suitable for #Configuration classes as it is a configuration related task.
You can refer Doc for detailed information.

Is Spring annotation #Controller same as #Service?

Is Spring annotation #Controller same as #Service?
I have idea about #Controller which can be used for URL mapping and invoking business logic.
while #Service used to annotate service class which contains business logic.
Can I use #Controller instead of #Service to annotate Service class?
No, they are pretty different from each other.
Both are different specializations of #Component annotation (in practice, they're two different implementations of the same interface) so both can be discovered by the classpath scanning (if you declare it in your XML configuration)
#Service annotation is used in your service layer and annotates classes that perform service tasks, often you don't use it but in many case you use this annotation to represent a best practice. For example, you could directly call a DAO class to persist an object to your database but this is horrible. It is pretty good to call a service class that calls a DAO. This is a good thing to perform the separation of concerns pattern.
#Controller annotation is an annotation used in Spring MVC framework (the component of Spring Framework used to implement Web Application). The #Controller annotation indicates that a particular class serves the role of a controller. The #Controller annotation acts as a stereotype for the annotated class, indicating its role. The dispatcher scans such annotated classes for mapped methods and detects #RequestMapping annotations.
So looking at the Spring MVC architecture you have a DispatcherServlet class (that you declare in your XML configuration) that represent a front controller that dispatch all the HTTP Request towards the appropriate controller classes (annotated by #Controller). This class perform the business logic (and can call the services) by its method. These classes (or its methods) are typically annotated also with #RequestMapping annotation that specify what HTTP Request is handled by the controller and by its method.
For example:
#Controller
#RequestMapping("/appointments")
public class AppointmentsController {
private final AppointmentBook appointmentBook;
#Autowired
public AppointmentsController(AppointmentBook appointmentBook) {
this.appointmentBook = appointmentBook;
}
#RequestMapping(method = RequestMethod.GET)
public Map<String, Appointment> get() {
return appointmentBook.getAppointmentsForToday();
}
This class is a controller.
This class handles all the HTTP Request toward "/appointments" "folder" and in particular the get method is the method called to handle all the GET HTTP Request toward the folder "/appointments".
I hope that now it is more clear for you.
If you look at the definitions of #Controller, #Service annotations, then you'll find that these are special type of #Component annotation.
#Component
public #interface Service {
….
}
 
#Component
public #interface Controller {
…
}
So what's the difference?
#Controller
The #Controller annotation indicates that a particular class serves the role of a controller. The #Controller annotation acts as a stereotype for the annotated class, indicating its role.
What’s special about #Controller?
You cannot switch this annotation with any other like #Service or #Repository, even though they look same.
The dispatcher scans the classes annotated with #Controller and detects #RequestMapping annotations within them. You can only use #RequestMapping on #Controller annotated classes.
#Service
#Services hold business logic and call method in repository layer.
What’s special about #Service?
Apart from the fact that it is used to indicate that it's holding the business logic, there’s no noticeable specialty that this annotation provides, but who knows, spring may add some additional exceptional in future.
Linked answer: What's the difference between #Component, #Repository & #Service annotations in Spring?
No, #Controller is not the same as #Service, although they both are specializations of #Component, making them both candidates for discovery by classpath scanning. The #Service annotation is used in your service layer, and #Controller is for Spring MVC controllers in your presentation layer. A #Controller typically would have a URL mapping and be triggered by a web request.
#Service vs #Controller
#Service : class is a "Business Service Facade" (in the Core J2EE patterns sense), or something similar.
#Controller : Indicates that an annotated class is a "Controller" (e.g. a web controller).
----------Find Usefull notes on Major Stereotypes
http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/stereotype/Component.html
#interface Component
#Target(value=TYPE)
#Retention(value=RUNTIME)
#Documented
public #interface Component
Indicates that an annotated class is a component. Such classes are considered as candidates for auto-detection when using annotation-based configuration and classpath scanning.
Other class-level annotations may be considered as identifying a component as well, typically a special kind of component: e.g. the #Repository annotation or AspectJ's #Aspect annotation.
#interface Controller
#Target(value=TYPE)
#Retention(value=RUNTIME)
#Documented
#Component
public #interface Controller
Indicates that an annotated class is a "Controller" (e.g. a web controller).
This annotation serves as a specialization of #Component, allowing for implementation classes to be autodetected through classpath scanning. It is typically used in combination with annotated handler methods based on the RequestMapping annotation.
#interface Service
#Target(value=TYPE)
#Retention(value=RUNTIME)
#Documented
#Component
public #interface Service
Indicates that an annotated class is a "Service", originally defined by Domain-Driven Design (Evans, 2003) as "an operation offered as an interface that stands alone in the model, with no encapsulated state."
May also indicate that a class is a "Business Service Facade" (in the Core J2EE patterns sense), or something similar. This annotation is a general-purpose stereotype and individual teams may narrow their semantics and use as appropriate.
This annotation serves as a specialization of #Component, allowing for implementation classes to be autodetected through classpath scanning.
#interface Repository
#Target(value=TYPE)
#Retention(value=RUNTIME)
#Documented
#Component
public #interface Repository
Indicates that an annotated class is a "Repository", originally defined by Domain-Driven Design (Evans, 2003) as "a mechanism for encapsulating storage, retrieval, and search behavior which emulates a collection of objects".
Teams implementing traditional J2EE patterns such as "Data Access Object" may also apply this stereotype to DAO classes, though care should be taken to understand the distinction between Data Access Object and DDD-style repositories before doing so. This annotation is a general-purpose stereotype and individual teams may narrow their semantics and use as appropriate.
A class thus annotated is eligible for Spring DataAccessException translation when used in conjunction with a PersistenceExceptionTranslationPostProcessor. The annotated class is also clarified as to its role in the overall application architecture for the purpose of tooling, aspects, etc.
As of Spring 2.5, this annotation also serves as a specialization of #Component, allowing for implementation classes to be autodetected through classpath scanning.
I already answered similar question on here Here is the Link
No both are different.
#Service annotation have use for other purpose and #Controller use for other.
Actually Spring #Component, #Service, #Repository and #Controller annotations are used for automatic bean detection using classpath scan in Spring framework, but it
doesn't ,mean that all functionalities are same.
#Service: It indicates annotated class is a Service component in the business layer.
#Controller: Annotated class indicates that it is a controller components, and mainly used at presentation layer.
You can declare a #service as #Controller.
You can NOT declare an #Controller as #Service
#Service
It is regular. You are just declaring class as a Component.
#Controller
It is a little more special than Component.
The dispatcher will search for #RequestMapping here.
So a class annotated with #Controller, will be additionally empowered with declaring URLs through which APIs are called
Controller will handle the navigation between the different views. Your mappings request mappings are handled with the help of controller.
Service interacts directly with the repository where usually the business logic is performed. You can add, delete, remove etc at the service layer
No you can't they are different. When the app was deployed your controller mappings would be borked for example.
Why do you want to anyway, a controller is not a service, and vice versa.
From Spring In Action
As you can see, this class is annotated with #Controller. On its own, #Controller doesn’t do much. Its primary purpose is to identify this class as a component for component scanning. Because HomeController is annotated with #Controller, Spring’s component scanning automatically discovers it and creates an instance of HomeController as a bean in the Spring application context.
In fact, a handful of other annotations (including #Component, #Service, and #Repository) serve a purpose similar to #Controller. You could have just as effectively annotated HomeController with any of those other annotations, and it would have still worked the same. The choice of #Controller is, however, more descriptive of this component’s role in the application.
Both are special form of #Component annotation.
Both #controller and #serviec, share same functionalities of #component annotation along with their own functionalities.
#Controller is a class-level annotation and it marks the class as web request handlers. For further explanation you can refer to this website: https://www.baeldung.com/spring-controller-vs-restcontroller
#Service is also a class-level annotation and it contains a business logic.
For further explanation you can refer to this website: https://www.baeldung.com/spring-component-repository-service

Resources