Spring Bean으로 등록하는어노테이션
。@Component,@Bean
@Component 클래스자동 식별 및Spring Context등록
。@ComponentScan
@Component이 내부에 선언되어 구체화된 목적을 더해Spring Bean으로 등록하는어노테이션
。어노테이션내부에@Component를 포함하여 자동으로@ComponentScan에 의해Spring Bean으로서 등록
。@Controller,@Service,@Repository,@Cofiguration
@Component:
。개발자가 직접 작성한클래스를Spring Bean으로 등록 시 선언하는어노테이션
▶Spring Stereotype Annotation:
선언 시@SpringBootApplication등으로부터@ComponentScan에 의해 자동으로 식별되어Spring Context로 등록
。 모든클래스에 선언이 가능
▶@Bean은메소드레벨,@Componen는클래스레벨에서 선언
。@Controller,@Service,@Repository,@Configuration의어노테이션은 내부에@Component가 포함되어 선언 시@Component에 의해Spring Bean으로 등록
▶@Component에서 따로 기능별로 역할구분하여Spring에게 해당어노테이션이 선언된클래스의 목적을 암시적으로 명시하는 목적으로구체화
Component Scan수행 시Spring Context에 등록되는어노테이션순서
。@Configuration -> @Controller -> @Service -> @Repository -> @Component순으로 선언된클래스가Spring Bean으로서 등록
▶단방향 의존성에 따라고수준 클래스로서Service 클래스 객체를 포함하는Controller 클래스가Service 클래스보다 먼저Spring Bean으로 등록되어야한다.
어노테이션을 선언하여Spring Bean등록 시싱글톤 패턴으로 관리됨.
。스프링 컨텍스트로 등록 시싱글톤 패턴으로 등록되어 하나의스프링 빈으로 관리됨
▶@Service,@Repository,@Controller
@ComponentScan(basePackages = "패키지경로"):
。Java Reflection 기술을 활용하여@Component가 선언된클래스를 자동으로식별후Spring Context에Spring Bean으로서 등록하는어노테이션
。@ComponentScan은@Component가 선언된클래스에 함께 선언되어식별되도록 설정.
▶ 이후 해당어노테이션이 선언된패키지 경로와basePackages = 패키지경로기준 동등하거나, 하위에 있는Spring Bean을 자동으로 식별하도록 지시
Spring Boot의Spring Bean을 식별 및 등록하는 원리
。진입점 클래스의@SpringBootApplication안에@ComponentScan이 포함
▶@SpringBootApplication을 포함하는패키지 경로기준 동등하거나, 하위패키지 경로범위내 모든@Component가 선언된Spring Bean이전역 Spring Context에 포함됨
ex )@SpringBootApplication를 포함하는진입점 클래스가package com.ktcloud.excercise;에 위치한 경우package com.ktcloud.excercise;의 하위패키지의Spring Bean들을전역 SpringContext로 등록@ComponentScan(basePackages = "com.ktcloud.excercise.step0") @SpringBootApplication public class ApplicationRunner { public static void main(String[] args) { SpringApplication.run(ApplicationRunner.class, args); } }▶
@ComponentScan을 통해 다른패키지 경로를진입점 클래스에 선언하여 다른패키지경로의하위경로범위상 모든Spring Bean들을전역 Spring Context에 등록
컨트롤러 어노테이션(@Controller,@RestController)
。클래스가Spring MVC의Controller를 포함하는Class일 경우 선언하여Spring Bean으로 등록하는어노테이션
▶어노테이션내부에@Component를 포함
。어노테이션선언 시Dispatcher Servlet,ViewResolver에게 등록되어 조회됨
。Spring MVC의레이어드 아키텍처상고수준 클래스이므로Service Class를 의존
▶클래스내Service 클래스 객체를필드로 선언 및의존성주입후요청을 전달
。컨트롤러 어노테이션이 선언된클래스는HTTP Request를 처리하기위해URL 패턴을 정의하는Controller들을 포함한다.
▶ 각Controller Method는@RequestMapping,@GetMapping, ... 등을 선언
@Controller:
。클래스내부Controller가 기본적으로View Resolver를 통해HTML View를 반환을 담당 시 선언하는어노테이션
▶Controller에서View이외를클라이언트에게 반환 시 따로@ResponseBody를 선언해야함.
@RestController
。클래스내부Controller가REST API를 담당하는 경우에 선언하는어노테이션
▶@Controller + @ResponseBody
。기본적으로@ResponseBody를 포함하는어노테이션으로 선언 시Controller Method에 자동적용되어 모든반환값을Jackson을 통해JSON,XML등의format으로 변환하여 반환
@Service:
。Spring MVC에서Business Logic을 담당하는Service Class를 정의 시 선언하여Spring Bean으로 등록하는어노테이션
▶어노테이션내부에@Component를 포함
▶Spring에Business Logic의 처리를 담당하는Spring Bean으로 지시
。Spring MVC의레이어드 아키텍처상Repository Class를 의존
▶클래스내Repository 클래스 객체를필드로 선언 및의존성주입후요청을 전달
@Repository:
。Spring MVC에서DB와의 상호작용을 담당하는Repository Class의 경우 선언하여Spring Bean으로 등록하는어노테이션
▶어노테이션내부에@Component를 포함
▶Spring에DAO(Data Access Obejct) 역할을 수행하는Spring Bean으로 지시
。@Component를 포함하는어노테이션중 가장 늦게Spring Bean으로 등록
。Spring MVC의레이어드 아키텍처상 가장저수준 클래스이므로 의존하지 않는다.
▶ 단Jdbc나JPA사용 시 해당구현체( ex.JdbcTemplate, ...)를필드로 선언하여의존성주입하여DB와 상호작용하여 사용
。@Repository가 선언된 경우Spring Framework에서 자동으로Exception을DataAccessException으로 변환
@Configuration
。외부 라이브러리또는class를Spring Context에 의해 관리되는Spring Bean으로 등록하는어노테이션
▶어노테이션내부에@Component를 포함
。어노테이션중 가장 먼저Spring Context에 등록
@Configuration -> @Controller -> @Service -> @Repository -> @Component
。설정을 주로 수행하는Configuration Class
▶외부 라이브러리등을Spring Bean으로 등록 시 활용
▶ 실무에서는커스텀한Spring Bean을 묶어주는 역할을 수행
。1개 이상의@Bean Method를 제공하는Class는 반드시@Configuration을 선언
▶ 내부에 여러 개의@Bean method를 정의하고@Bean Method를 통해Spring Bean을 생성 및Spring Context에 등록
@Configuration(proxyBeanMethods=true)
。full mode로서 내부@Bean에서Singleton의Spring Bean을 반환
▶proxyBeanMethods=false인 경우 호출할때마다 새로운Spring Bean을 생성
@Bean:
。Configuration Class내부에Method 레벨에서Method에 선언하여메서드 반환값을Spring Bean을 등록하는 역할을 수행
▶@Bean이 선언된 Method는Spring Context에 의해 관리되는Spring Bean으로 등록
。보통외부 라이브러리를Spring Bean 객체로 만들 때 사용.
@Bean(name = "nm"):
。Spring Context내Spring Bean의 이름은카멜케이스로 작성됨
▶ 정의된SpringBean의 명칭을 사용자 임의로 변경하여 설정.
@Bean의의존성 주입방식
。@Bean또는@Autowired가 선언된메서드의매개변수에 정의된자바 객체를 자동으로Spring Context내 등록된Spring Bean으로의존성 주입
▶Spring Bean은Singleton 패턴으로 관리되므로, 항상싱글톤 객체로서 주입// Spring Context로 부터 매개변수에 // 해당 Type을 가진 Spring Bean을 주입 @Bean public FrontDesk frontDesk(Chief chief){ return new FrontDesk(chief); }