์ง์ ์ ๋ง์ง๋ง์์ ๋ค๋ฃฌ ์ ์ฌ์ ์ธ ๋ฌธ์ ์ , ์ฆ Controller ์ code ๊ฐ ๋๋ฌด ๋ณต์กํด์ง๋ ๋ฌธ์ ์ ์ ์ด๋ป๊ฒ ํด๊ฒฐํ ์ ์์๊น?
Purpose of Service Layer

Service Layer ๋ Facade Design Patter ์ ์ฌ์ฉํ ์ ํ์ ์ธ ์์์ด๋ค.
Facade Pattern ์ด๋, ๋ณต์กํ system ์ด๋ subsystem ์ Interface ๋ฅผ ํ๋์ ๋จ์ํ ๊ณ ์์ค์ Interface ๋ก ๋ฌถ์ด system ์ ๊ฒฐํฉ๋๋ฅผ ๋ฎ์ถ๊ณ code ์ ๊ฐ๋ ์ฑ๊ณผ ์ ์ง๋ณด์์ฑ์ ๋์ผ ์ ์๋ Design Pattern ์ด๋ค.
๋ฐ๋ผ์, Controller ๋ DAO ์ ๋ณต์กํ buisness logic ์ ์์ง ๋ชปํ์ฌ๋, Service Layer ๊ฐ ์ ๊ณตํ๋ ๋จ์ํ method ๋ง ์ฌ์ฉํ๋ฉด ๋๋ ๊ฒ์ด๋ค.
๋ํ Service Layer ๋ DAO/repository ๋ฑ์ data source ๋ค์ integrate ํ๋๋ฐ, Controller ๋ด๋ถ์์ ์ง์ DAO ๋ฅผ Injection ๋ฐ์ ์ฌ์ฉํ๋ ๋์ , Service Layer ๊ฐ DAO ๋ค์ ์ข ํฉ์ ์ผ๋ก ๊ด๋ฆฌํ์ฌ Controller ์์๋ ๋จ์ํ method ๋ง ํธ์ถํ๋ ๊ฒ์ผ๋ก buisness logic ์ ์ฒ๋ฆฌํ ์ ์๊ฒ๋ํ๋ค.

์ ๋ฆฌํ๋ฉด, ์์ ์ด๋ฏธ์ง์ ๋ณด๋ ๊ฒ์ฒ๋ผ, Controller ๋ ๋จ์ํ multiple data sources ๋ค์ integrate ํ Service Later object ํ๋๋ง ๋ฐ๋ผ๋ณด๋ฉด ๋๋ค๋ ๊ฒ์ด๋ค.

Service Layer ๋ก ์ฌ์ฉํ class ์๋ @Service annotation ์ ์ฌ์ฉํด์ผ ํ๋๋ฐ, @Service ๋ ์์ ๊ฐ์ด @Component ์ Specialization ๋ annotation ์ ํํ์ด๋ค.
๋ฐ๋ผ์ component-scanning ๋๋ถ์ Service object ๋ Spring Bean ์ ๋ฑ๋ก๋์ด Spring Container ์ ์ํ์ฌ ๊ด๋ฆฌ๋๋ค.
Implement Employee Service
๊ทธ๋ผ ์ด์ Employee Service ๋ฅผ ๊ตฌํํด๋ณด์.
Step 1: Define Service Interface
public interface EmployeeService {
List<Employee> findAll();
}Step 2: Define Service Implementation
@Service
public class EmployeeServiceImpl implements EmployeeService {
private EmployeeDAO employeeDAO;
public EmployeeServiceImpl(EmployeeDAO employeeDAO) {
this.employeeDAO = employeeDAO;
}
@Override
public List<Employee> findAll() {
return employeeDAO.findAll();
}
}@Service annotation ์ ์ฌ์ฉํ๊ณ , EmployeeDAO ๋ฅผ Service ์์ injection ๋ฐ์์ findAll() ์ด๋ผ๋ method ๋ฅผ ์ ๊ณตํ๋๋ก ๋ง๋ ๋ค.
Step 3: Update REST Controller
private EmployeeService employeeService;
public EmployeeRestController(EmployeeService employeeService) {
this.employeeService = employeeService;
}EmployeeDAO ๋ฅผ declare ํ๊ณ injection ํ๋ ๋์ , EmployeeService ๋ฅผ declare ํ๊ณ injection ํ๋ ๋ฐฉ๋ฒ์ผ๋ก ์ฌ์ฉํ๋ค. ์ด๋ ๊ฒ ๋๋ฉด ์ต์ข
์ ์ผ๋ก Controller ๋ Service ๋ฅผ ๋ฐ๋ผ๋ณด๊ฒ ๋๊ณ , Service ๋ ๊ฐ๊ฐ์ DAO ๋ฅผ ๋ฐ๋ก๋ณด๊ฒ ๋๋ ๊ฒ์ด๋ค.
์ด์ requirements ์ ๋ํ์ฌ ์ด๋ค ํ๋ฆ์ผ๋ก ๊ตฌํํ๋ฉด ๋๋์ง ํ์ ํ๋ค. ์ด์ requirements ์ ๋๋จธ์ง ๋ถ๋ถ์ ๋ชจ๋ ๊ตฌํํ์ฌ๋ณด์.