Spring Bean으로 등록하는어노테이션
。@Component,@Bean
Spring Bean의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으로 등록되어야한다.
@ComponentScan("패키지경로"):
。어플리케이션실행 시 선언한클래스기준패키지 경로의 하위에 있는Spring Bean을Spring Context에 자동으로식별및등록되도록하는어노테이션
。Spring Context 구현체( ex.AnnotationConfigApplicationContext)가 위치한클래스에 선언 시 해당구현체내부로 포함
Spring 어플리케이션의Spring Bean을 식별 및 등록하는 원리
。진입점 클래스의@SpringBootApplication안에@ComponentScan이 포함
▶@SpringBootApplication을 포함하는패키지 경로기준 하위패키지 경로범위내 모든@Component와파생형이 선언된Spring Bean이전역 Spring Context에 포함됨
ex )@SpringBootApplication를 포함하는진입점 클래스가package com.ktcloud.excercise;에 위치한 경우package com.ktcloud.excercise;의 하위패키지의Spring Bean들을전역 SpringContext로 등록@ComponentScan("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를 포함
▶Spring에Web 요청과응답을 담당하는Spring Bean으로 지시
。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를 포함
。@Component를 포함하는어노테이션중 가장 먼저Spring Context에 등록
@Configuration -> @Controller -> @Service -> @Repository -> @Component
。설정을 주로 수행하는Configuration Class로서 내부에 여러개의@Bean method를 정의하여 직접Spring Bean을 생성 및 등록하는 역할
▶ 1개 이상의@BeanMethod를 제공하는Class는 반드시@Configuration을 선언
。실무에서는커스텀한Spring Bean을 묶어주는 역할을 수행
。XML대신외부 라이브러리등을Spring Bean으로 등록 시에도 활용
@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의의존성 주입방식
。해당 2가지의 기법으로Autowiring이 가능.
method call
。동일Configuration Class내@Bean 메소드를 직접 호출하여의존성 주입
。@Configuration(proxyBeanMethods=true)인 경우@Bean Method호출 시Spring Bean을Singleton으로 주입
▶proxyBeanMethods=false인 경우 일반Java 메소드 호출과 동일// method call : @Bean public Person person2MethodCall(){ return new Person(name(),age(),address()); }
method parameters
。Spring Context가매개변수를 확인 후 알맞은Spring Bean을 찾아서 주입
▶ 항상Singleton으로 주입// method parameters : @Bean public Person person3Parameters(String name , int age , Address address2){ return new Person(name,age,address2); }