Service Layer

This Service Layer act as a bridge between the DAO (Persistence) layer and the Presentation (Web) layer. Even in service layer similar to DAO layer we have the interface and its implementation.

In the ServiceImpl class, we are using mainly three Spring annotations: @Service, @Transactional and @Autowired

@Service:

  • Indicates that the annotated class PhoneServiceImpl is a "Service".
  • A stereotype of @Component for persistence layer

@Transactional:

  • Enables Spring's transactional behaviour.
  • Can be applied to a class, an interface or a method.
  • This annotation is enabled by setting in the context configuration file.
  • The attribute readOnly = true which sets the transaction to read only mode so that it cannot modify data in any case.

@Autowired*

  • Marks the field as to be autowired by Spring's dependency injection facilities.
  • The field is injected right after construction of the bean, before any config methods are invoked.
  • Autowires the bean by matching the data type in the configuration metadata.

PhoneService.java

package com.spring.demo.service;

import java.util.List;

import com.spring.demo.model.Phone;

public interface PhoneService {

    public void addPhone(Phone p);
    public void updatePhone(Phone p);
    public List<Phone> listPhones();
    public Phone getPhoneById(int id);
    public void removePhone(int id);

}

PhoneServiceImpl.java

package com.spring.demo.service;

import java.util.List;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.spring.demo.dao.PhoneDAO;
import com.spring.demo.model.Phone;

@Service
public class PhoneServiceImpl implements PhoneService {

    @Autowired
    private PhoneDAO phoneDAO;

    public void setPhoneDAO(PhoneDAO phoneDAO) {
        this.phoneDAO = phoneDAO;
    }

    @Override
    @Transactional
    public void addPhone(Phone p) {
        this.phoneDAO.addPhone(p);
    }

    @Override
    @Transactional
    public void updatePhone(Phone p) {
        this.phoneDAO.updatePhone(p);
    }

    @Override
    @Transactional
    public List<Phone> listPhones() {
        return this.phoneDAO.listPhones();
    }

    @Override
    @Transactional
    public Phone getPhoneById(int id) {
        return this.phoneDAO.getPhoneById(id);
    }

    @Override
    @Transactional
    public void removePhone(int id) {
        this.phoneDAO.removePhone(id);
    }

}

results matching ""

    No results matching ""