[Spring Boot] 3. 빈 생성, 접근 방법

boing·2023년 9월 21일

Spring Boot

목록 보기
3/3

1. 빈 생성

  • @SpringBootApplication의 빈의 패키지와 같거나 서브패키지(권장)로 만들어야 자동으로 빈 생성
  • com.exam
    ㄴBootTemplateApplication.java (@SpringBootApplication)
  • com.exam.service
    ㄴ xxxServiceImpl.java (@Service)
  • com.exam.dao
    ㄴ xxxDAO.java (@Repository)

==> com.exam의 서브패키지인 com.exam.service 에 있는 파일 => 자동 빈 생성


2. 의존성 주입 (DI, Dependency Injection)

가. @Autowired 이용

@Service
public class DeptServiceImpl implements DeptService {

	@Autowired
	DeptDAO dao;
}	

나. 생성자 이용 ***

  • 스프링 프레임워크 4.3 이후 사용 가능
  • 생성자만 만드는 것임. 어노테이션 지정 안함
  • 기본생성자는 없어야 함. 기본생성자 있으면 기본생성자를 실행하니까..
@Service
public class DeptServiceImpl {

	DeptDAO dao;
    
	//기본생성자 제거 필수
	//생성자 (@Autowired 필요 없음)
	public DeptServiceImpl(DeptDAO dao) {
		System.out.println("DeptServiceImpl 생성자로 자동 주입");
		this.dao = dao;
	}

3. 빈 접근 방법

가. Spring Framwork

main(){
	ApplicationContext ctx = new GenerieXmlApplicationContext("dept.xml");
	DeptService service = ctx.getBean("xxx", DeptService.class);

나. Spring Boot

//Application에서 빈(DeptService) 사용
main(){
	ApplicationContext ctx = SpringApplication.run(Application.class, args);
	DeptService service = ctx.getBean("xxx", DeptService.class);

profile
keep coding

0개의 댓글