스프링 기본

수돌임깅·2023년 8월 31일
0

스프링

목록 보기
2/2

servlet-context.xml의 base-package

1.프로젝트 실행시 지정한 패키지 이하의 모든 클래스를 스캔하며, @Controller,@Service,@Repository,@Component 어노테이션(Annotation)이 붙은 클래스들을 스프링빈으로 등록해줌.
2.스프링빈(Spring Bean):스프링에서 관리하는 객체로 프로젝트 실행시 객체를 1개만 생성하는 싱글톤 형태로 생성됨

스프링 의존관계 주입(Dependency Injection)

a. 스프링이 관리하는 객체가 가지고 있는 자원을 호출하기 위해 해당 객체에 대한 사용을 할 수텍스트 있는 것
b. 주의사항
- 주입받으려는 클래스는 반드시 스프링빈(스프링이 관리하는 객체)이어야함.

  • 필드 주입
@Controller
public class ExampleController{

	// ExampleService 객체 주입
    @Autowired
    private ExampleService exampleService;


	@GetMapping("/req1")
    public String req1(){
    	//서비스클래스의 method1을 호출해야함.
        exampleService.method1();
    }
}

@Service
public class ExampleService {
	public void method1() {
    	
    }
}
  • 생성자 주입
@Controller
@RequiedArgsConstructor
public class ExampleController{

	// ExampleService 객체 주입
    private final ExampleService exampleService;


	@GetMapping("/req1")
    public String req1(){
    	//서비스클래스의 method1을 호출해야함.
        exampleService.method1();
    }
}

@Service
public class ExampleService {
	public void method1() {
    	
    }
}
profile
초보 개발자

0개의 댓글