Trong quá trình lập trình sử dụng Spring Framework, đặc biệt là lập trình Spring MVC để xây dựng một ứng dụng web thì việc thường xuyên sử dụng các Annotation trong spring là điều khó tránh khỏi.
Dưới đây là một số Annotation trong Spring thường dùng đi kèm với các ví dụ cụ thể
@Autowired
@Autowired: Annotation này trong spring giúp tự động liên kết các Bean lại với nhau, đây là một trong những đặc điểm nỗi bật của Spring để thể hiện tính chất DI và IOC (Dependency Injection và Inversion of Control).
Ví dụ về annotation @Autowired:
public class FooService {
private FooFormatter fooFormatter;
@Autowired
public FooService(FooFormatter fooFormatter) {
this.fooFormatter = fooFormatter;
}
}
@Scope
@Scope: đây là môt Annotation mặc định trong Spring, hầu hết scope phổ biến cho các autodetected components là singleton (singleton: Với mỗi bean container chỉ tao duy nhất một đối tượng), để thay đổi phạm vi ta sử dụng @Scope.
Ví dụ về annotation @Scope:
@Bean
@Scope("singleton")
public Person personSingleton() {
return new Person();
}
@Component
@Component: dùng để scan các components.
Ví dụ về annotation @Component:
@Component("fooFormatter")
public class FooFormatter {
public String format() {
return "foo";
}
}
@Component
public class FooService {
@Autowired
private FooFormatter fooFormatter;
}
@Repository
@Repository: dùng để scan các components để đánh dấu các lớp DAO/Repository của Spring.
Ví dụ về annotation @Repository:
public interface EmployeeDAO
{
public EmployeeDTO createNewEmployee();
}
@Repository ("employeeDao")
public class EmployeeDAOImpl implements EmployeeDAO
{
public EmployeeDTO createNewEmployee()
{
EmployeeDTO e = new EmployeeDTO();
e.setId(1);
e.setFirstName("Lokesh");
e.setLastName("Gupta");
return e;
}
}
@Service
@Service: dùng để scan các components để đánh dấu các Service của lớp business.
Ví dụ về annotation @Service:
public interface EmployeeManager
{
public EmployeeDTO createNewEmployee();
}
@Service ("employeeManager")
public class EmployeeManagerImpl implements EmployeeManager
{
@Autowired
EmployeeDAO dao;
public EmployeeDTO createNewEmployee()
{
return dao.createNewEmployee();
}
}
@Transactional
@Transactional: Annotation này trong spring giúp đánh dấu các class có sử dụng đến Transaction do Spring quản lý.
Ví dụ về annotation @Transactional:
public class CustomerManagerImpl implements CustomerManager {
private CustomerDAO customerDAO;
public void setCustomerDAO(CustomerDAO customerDAO) {
this.customerDAO = customerDAO;
}
@Override
@Transactional
public void createCustomer(Customer cust) {
customerDAO.create(cust);
}
}
@Controller
@Controller: đây là môt Annotation trong spring mvc dùng để đánh dấu đây là lớp có chức năng là Controller.
Ví dụ về annotation @Controller:
@Controller ("employeeController")
public class EmployeeController
{
@Autowired
EmployeeManager manager;
public EmployeeDTO createNewEmployee()
{
return manager.createNewEmployee();
}
}
@RequestMapping
@RequestMapping: đây là môt Annotation trong spring mvc dùng để cấu hình URL tương ứng với @WebServlet và mapping trong file xml với JSP/servlet.
@RequestMapping(value="/method0")
@ResponseBody
public String method0(){
return "method0";
}
@RequestMapping(value={"/method1","/method1/second"})
@ResponseBody
public String method1(){
return "method1";
}
@RequestParam
@RequestMapping(value="/method9")
@ResponseBody
public String method9(@RequestParam("id") int id){
return "method9 with id= "+id;
}
@InitBinder
@InitBinder
public void dataBinding(WebDataBinder binder) {
binder.addValidators(userValidator, emailValidator);
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
dateFormat.setLenient(false);
binder.registerCustomEditor(Date.class, "dob", new CustomDateEditor(dateFormat, true));
}
@SessionAttribute
@SessionAttribute("myModel")
@Controller
public class MyController {
@RequestMapping(...)
public String displayForm(@RequestParam("id") long id, ModelMap model) {
MyModel m = findById(id);
model.put("myModel", m); // Initialized
return ...;
}
@RequestMapping(...)
public String submitForm(@ModelAttribute("myModel") @Valid MyModel m,
BindingResult errors, SessionStatus status) {
if (errors.hasErrors()) {
// Will render a view with updated MyModel
return ...;
} else {
status.setComplete(); // MyModel is removed from the session
save(m);
return ...;
}
}
}
@Valid
@Controller
@RequestMapping("/customer")
public class SignUpController {
@RequestMapping(value = "/signup", method = RequestMethod.POST)
public String addCustomer(@Valid Customer customer, BindingResult result) {
if (result.hasErrors()) {
return "SignUpForm";
} else {
return "Done";
}
}
@RequestMapping(method = RequestMethod.GET)
public String displayCustomerForm(ModelMap model) {
model.addAttribute("customer", new Customer());
return "SignUpForm";
}
}
@ModelAttribute
@ModelAttribute: đây là môt Annotation trong spring mvc dùng để lấy các tham số và trả về một đối tượng (Object).
@Controller
@ControllerAdvice
public class EmployeeController {
private Map<Long, Employee> employeeMap = new HashMap<>();
@RequestMapping(value = "/addEmployee", method = RequestMethod.POST)
public String submit(
@ModelAttribute("employee") Employee employee,
BindingResult result, ModelMap model) {
if (result.hasErrors()) {
return "error";
}
model.addAttribute("name", employee.getName());
model.addAttribute("id", employee.getId());
employeeMap.put(employee.getId(), employee);
return "employeeView";
}
@ModelAttribute
public void addAttributes(Model model) {
model.addAttribute("msg", "Welcome to the Netherlands!");
}
}
Trên là một số annotation trong spring framework thường dùng, tất nhiên vẫn còn rất nhiều annotation khác, tuy nhiên tôi không nhắc đến trong bài viết này. Hy vọng với một số annotation mà tôi đưa ra ở trên sẽ giúp các bạn giải đáp một số thắc mắc và áp dụng vào thực tế ứng dụng web.


