Spring
230202 Spring Service, DAO 사용어노테이션
주영재
2023. 2. 2. 19:51
Service객체
@Service : 서비스 클래스에 사용한다.
@Repository : DAO클래스 또는 리포지토리 클래스에 사용한다.
@Controller, @Service, @Repository, @Component 는 뭘 써도 다 똑같이 동작한다. 해당 파일을 구별하기 위함.
컴포넌트 스캔 등록을 해야함을 주의.
<context:component-scan base-package="com.simple.score.service"/>
서비스계층 구현
방법1 : new 연산자를 이용한 service 객체 생성 및 참조
spring에서 사용하지 않음. 더 좋은 방법이 있기 때문
방법2 : 스프링 설정파일을 이용한 서비스 객체 생성 및 의존 객체 자동 주입
servlet-context.xml에서
<!-- 2nd -service영역을 bean으로 생성 -->
<beans:bean class="com.simple.score.service.ScoreServiceImpl"/>
-bean 생성
-bean의 id는 이름
컨트롤러에서 서비스 변수 위에
@Autowired만 해주면 된다.
@Autowired
private ScoreService service;
방법3 : 어노테이션을 이용해서 서비스 객체 생성 및 의존 객체 자동 주입
컴포넌트 스캔을 등록할 때
servlet-context.xml에서 스캔명령을
<context:component-scan base-package="com.simple.*"/>
로 하면 다 읽음. 컴포넌트 스캔이 여러개가 될 때 앞에 com.simple이란 이름이 같으면 *로 처리가능.
@Service 옵션
value=""으로 빈 생성을 할때 이름을 지정. bean의 id로 이름을 지정하는 것과 같음.
속성을 하나만 주면 @Service("")로 사용가능
마찬가지로 @Autowired의 짝인 @Qualifier("이름")으로도 연결이 가능함.
+)어차피 @Autowired는 속성을 찾아서 알아서 해주긴 함.
package com.simple.score.service;
import org.springframework.stereotype.Service;
//@Controller
//@Repository
//@Component
@Service("service") //빈의 이름명시
public class ScoreServiceImpl implements ScoreService {
}
@Autowired
@Qualifier("service")
private ScoreService service;
이런 식으로.
DAO객체
DAO클래스에서는
@Repository 어노테이션 사용.
package com.simple.score.dao;
import org.springframework.stereotype.Repository;
@Repository("scoreDAO")
public class ScoreDAOImpl implements ScoreDAO{
}