noscript
Stereotype Annotations help us to get the roles of types or methods at conceptual level. Stereotype annotations are @Component, @Service, @Repository and @Controller annotations. These annotations are used for auto-detection of beans using @ComponentScan and component-scan. The Spring stereotype @Component is a parent stereotype. The other stereotypes i.e @Service, @Repository and @Controller are the specialisation of @Component annotation. The @ComponentScan is used while designing the application with java configuration and component-scan is used to scan the component automatically in XML. The basic requirement is to provide the base package name while we are using @ComponentScan and component-scan. Here we will describe the usability of stereotype annotations with complete example.

Contents

• @Component
• @Service
• @Repository
• @Controller
• @ComponentScan and component-scan

• Complete Example

@Component

@Component annotation is a stereotype and is used at class level that makes the class a component. These classes are eligible for auto-detection through classpath scanning. In java configuration, @ComponentScan annotation is used to auto detect the component and in spring application context XML, component-scan tag is used for auto-detection through classpath. @Component annotation helps us to create the spring bean automatically without mentioning it in the xml configuration. So you get rid of the configuration doing all the time you create the class.
@Component

public class BookUtility {}

@Service

@Service annotation is a stereotype and is used at class level that makes the class a service. A service class can act as Business Service Facade of j2EE pattern. The actual implementation of the business logic using DAO is done with the help of service class. The classes annotated with @Service are auto detected through classpath scanning. Annotating a class with @Service gives a logical sense that these classes are services. If we use @Component annotation on service class instead of @Service, there is no harm but for better readability, a service class should be annotated with @Service annotation. We can say that  @Service annotation is a specialisation of @Component annotation. @Service annotation has the attribute as value which is the suggestion of component name as well as a spring bean name for that class.

@Repository

@Repository annotation is a stereotype and is used at class level. The class having the role of  store, fetch or search data, comes to the repository category. We have to annotate the classes that are performing these of tasks with @Repository annotation for auto-detection through classpath scanning. DAO classes should be annotated with @Repository annotation for auto-detection. @Repository annotation is the specialisation of @Component annotation. @Repository annotation has an attribute value which is the suggestion of component name as well as spring bean name for that class.

@Controller

@Controller annotation is a stereotype and is used at class level in spring MVC. It indicates that the class is a web controller. These classes annotated with @Controller are auto detected through classpath scanning. @Controller annotation is usually used in combination with @RequestMapping annotation in spring MVC. @Controller annotation is a specialisation of @Component annotation. @Controller annotation has an attribute value which is the suggestion for component name and will also be used as spring bean name for that class.

Example

package com.org.example.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = “students”)
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = “first_name”, nullable = false)
private String firstName;
@Column(name = “last_name”)
private String lastName;
@Column(name = “email”)
private String email;
public Student() {
}
public Student(String firstName, String lastName, String email) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
package com.org.example.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import com.org.example.entity.Student;
import com.org.example.service.StudentService;
@Controller
public class StudentController {
private StudentService studentService;
public StudentController(StudentService studentService) {
super();
this.studentService = studentService;
}
@GetMapping(“/”)
public String listStudents1(Model model) {
model.addAttribute(“students”, studentService.getAllStudents());
return “students”;
}
// handler method to handle list students and return mode and view
@GetMapping(“/students”)
public String listStudents(Model model) {
model.addAttribute(“students”, studentService.getAllStudents());
return “students”;
}
@GetMapping(“/students/new”)
public String createStudentForm(Model model) {
// create student object to hold student form data
Student student = new Student();
model.addAttribute(“student”, student);
return “create_student”;
}
@PostMapping(“/students”)
public String saveStudent(@ModelAttribute(“student”) Student student) {
studentService.saveStudent(student);
return “redirect:/students”;
}
@GetMapping(“/students/edit/{id}”)
public String editStudentForm(@PathVariable Long id, Model model) {
model.addAttribute(“student”, studentService.getStudentById(id));
return “edit_student”;
}
@PostMapping(“/students/{id}”)
public String updateStudent(@PathVariable Long id,
@ModelAttribute(“student”) Student student,
Model model) {
// get student from database by id
Student existingStudent = studentService.getStudentById(id);
existingStudent.setId(id);
existingStudent.setFirstName(student.getFirstName());
existingStudent.setLastName(student.getLastName());
existingStudent.setEmail(student.getEmail());
// save updated student object
studentService.updateStudent(existingStudent);
return “redirect:/students”;
}
// handler method to handle delete student request
@GetMapping(“/students/{id}”)
public String deleteStudent(@PathVariable Long id) {
studentService.deleteStudentById(id);
return “redirect:/students”;
}
}
package com.org.example.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.org.example.entity.Student;
@Repository
public interface StudentRepository extends JpaRepository<Student, Long>{
}
package com.org.example.service;
import java.util.List;
import com.org.example.entity.Student;
public interface StudentService {
List<Student> getAllStudents();
Student saveStudent(Student student);
Student getStudentById(Long id);
Student updateStudent(Student student);
void deleteStudentById(Long id);
}
package com.org.example.service.impl;
import java.util.List;
import org.springframework.stereotype.Service;
import com.org.example.entity.Student;
import com.org.example.repository.StudentRepository;
import com.org.example.service.StudentService;
@Service
public class StudentServiceImpl implements StudentService{
private StudentRepository studentRepository;
public StudentServiceImpl(StudentRepository studentRepository) {
super();
this.studentRepository = studentRepository;
}
@Override
public List<Student> getAllStudents() {
return studentRepository.findAll();
}
@Override
public Student saveStudent(Student student) {
return studentRepository.save(student);
}
@Override
public Student getStudentById(Long id) {
return studentRepository.findById(id).get();
}
@Override
public Student updateStudent(Student student) {
return studentRepository.save(student);
}
@Override
public void deleteStudentById(Long id) {
studentRepository.deleteById(id);
}

}

                                                          For more information & classes Call: 2048553004
                                                                           Registration Link: Click Here!

Author: Jyotsna Binjwe

Software Development Trainer

IT Education Centre Placement & Training Institute

© Copyright 2024 | IT Education Centre.