Implementing Service Layer Components in SSH Frameworks
Defining the Service Interafce
The service layer acts as a bridge between presentation and data layers, encapsulating bussiness logic. Start by defining a clean interface.
package com.example.app.service;
import com.example.app.domain.ApplicationRecord;
public interface RecordService {
public static final String BEAN_NAME = "recordService";
void persistRecord(ApplicationRecord record);
}
Implementing the Service Interface
The implementation injects the data access object (DAO) and handles transaction management.
package com.example.app.service.impl;
import com.example.app.dao.RecordDao;
import com.example.app.domain.ApplicationRecord;
import com.example.app.service.RecordService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
@Transactional(readOnly = true)
@Service(RecordService.BEAN_NAME)
public class RecordServiceImpl implements RecordService {
@Resource(name = RecordDao.BEAN_NAME)
private RecordDao recordDao;
@Override
@Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, readOnly = false)
public void persistRecord(ApplicationRecord record) {
recordDao.persist(record);
}
}
Testing the Service Implementation
A JUnit test validates the service layer's integration with the DAO and transaction behavior.
package com.example.app.test;
import com.example.app.domain.ApplicationRecord;
import com.example.app.service.RecordService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.time.Instant;
public class ServiceLayerTest {
@Test
public void testServicePersist() {
ApplicationContext ctx = new ClassPathXmlApplicationContext("application-context.xml");
RecordService service = (RecordService) ctx.getBean(RecordService.BEAN_NAME);
ApplicationRecord record = new ApplicationRecord();
record.setRecordName("Service Layer Test");
record.setRecordDescription("Testing service transaction and persistence.");
record.setRecordTimestamp(Instant.now());
service.persistRecord(record);
}
}
Project Structure
src/main/java/com/example/app/service/– Contains service interfaces.src/main/java/com/example/app/service/impl/– Contains service implementations.src/main/resources/– Holds Spring configuration files (e.g.,application-context.xml).src/test/java/– Contains unit tests like the service test.