섹션2 : Java Spring Framework 시작하기
8단계 - 첫 번째 Java Spring Bean 및 Java Spring 설정 시작
-
- Spring 애플리케이션이나 Spring 컨텍스트를 실행하는 단계
- JVM 내에 Spring 컨텍스트를 만드는 과정이다.
- var context = new AnnotationConfigApplicationContext(HelloWorldConfiguration.class);
- Spring 애플리케이션이나 Spring 컨텍스트를 실행하는 단계
-
- Spring 프레임워크 관리하도록 할 것을 설정
- String에 Bean을 관리하라는 명령을 내린다.
- Spring 프레임워크 관리하도록 할 것을 설정
Spring은 특정 객체 name을 관리한다.
Spring Bean이란?
빈(Bean)은 스프링 컨테이너에 의해 관리되는 재사용 가능한 소프트웨어 컴포넌트이다.
즉, 스프링 컨테이너가 관리하는 자바 객체를 뜻하며, 하나 이상의 빈(Bean)을 관리한다.
빈은 인스턴스화된 객체를 의미
코드
package com.in28minutes.learnspringframework;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class App02HelloWorldSpring {
public static void main(String[] args) {
//1. Launch a Spring Context
var context = new AnnotationConfigApplicationContext(HelloWorldConfiguration.class);
//2. Configure the things that we want Spring to manage -
//HelloWorldConfiguration - @Configuration
//name - @Bean 빈은 context.getBean을 사용하고 Bean의 이름을 부여해 검색.
//3. Retrieving Beans managed by Spring
//이때, 함수명으로 사용한 이 이름이 틀리면 에러 발생생
System.out.println(context.getBean("name"));
}
}
package com.in28minutes.learnspringframework;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class HelloWorldConfiguration {
@Bean
public String name() {
return "Ranga";
}
}
- console 결과
17:17:12.499 [main] DEBUG org.springframework.context.annotation.AnnotationConfigApplicationContext -- Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@363ee3a2
17:17:12.529 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory -- Creating shared instance of singleton bean 'org.springframework.context.annotation.internalConfigurationAnnotationProcessor''org.springframework.context.annotation.internalCommonAnnotationProcessor'
17:17:12.793 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory -- Creating shared instance of singleton bean 'helloWorldConfiguration'
17:17:12.801 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory -- Creating shared instance of singleton bean 'name'
Ranga
9단계 - Spring Java 설정 파일에서 더 많은 Java Spring Bean 만들기
Java의 record
DTO 작성 시, 반복코드를 줄이기 위해 JDK16부터 도입된 기능으로 Private final 필드를 자동생성하고, 생성자, Getter, Setter, Hashcode(), equals(), toString() 을 자동으로 추가해준다.
record Person (String name, int age) {};
실습 코드
package com.in28minutes.learnspringframework;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class App02HelloWorldSpring {
public static void main(String[] args) {
//1. Launch a Spring Context
var context = new AnnotationConfigApplicationContext(HelloWorldConfiguration.class);
//2. Configure the things that we want Spring to manage -
//HelloWorldConfiguration - @Configuration
//name - @Bean 빈은 context.getBean을 사용하고 Bean의 이름을 부여해 검색.
//3. Retrieving Beans managed by Spring
System.out.println(context.getBean("name"));
System.out.println(context.getBean("age"));
System.out.println(context.getBean("person"));
System.out.println(context.getBean("address"));
}
}
package com.in28minutes.learnspringframework;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
record Person (String name, int age) {};
//Address - firstLine & city
record Address(String firstLine, String city ) {};
@Configuration
public class HelloWorldConfiguration {
@Bean
public String name() {
return "Ranga";
}
@Bean
public int age() {
return 15;
}
@Bean
public Person person() {
return new Person("Ravi", 20);
}
@Bean
public Address address() {
return new Address("Barker Street", "London");
}
}
- 콘솔 결과
17:20:44.921 [main] DEBUG org.springframework.context.annotation.AnnotationConfigApplicationContext -- Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@363ee3a2
17:20:44.951 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory -- Creating shared instance of singleton bean 'org.springframework.context.annotation.internalConfigurationAnnotationProcessor'
17:20:45.189 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory -- Creating shared instance of singleton bean 'org.springframework.context.event.internalEventListenerProcessor'
17:20:45.193 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory -- Creating shared instance of singleton bean 'org.springframework.context.event.internalEventListenerFactory'
17:20:45.195 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory -- Creating shared instance of singleton bean 'org.springframework.context.annotation.internalAutowiredAnnotationProcessor'
17:20:45.198 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory -- Creating shared instance of singleton bean 'org.springframework.context.annotation.internalCommonAnnotationProcessor'
17:20:45.215 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory -- Creating shared instance of singleton bean 'helloWorldConfiguration'
17:20:45.224 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory -- Creating shared instance of singleton bean 'name'
17:20:45.233 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory -- Creating shared instance of singleton bean 'age'
17:20:45.234 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory -- Creating shared instance of singleton bean 'person'
17:20:45.237 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory -- Creating shared instance of singleton bean 'address'
Ranga
15
Person[name=Ravi, age=20]
Address[firstLine=Barker Street, city=London]
10단계 - Spring Framework Java 구성 파일에서 자동 연결 구현
- 객체의 이름을 변경하고 싶은 경우. 빈의 사용자 이름 설정하기
@Bean(name = "address2")
public Address address() {
return new Address("Barker Street", "London");
}
이 경우, 빈을 가져올 때,
System.out.println(context.getBean("address2");
이렇게 가져와도 되지만,
System.out.println(context.getBean(Address.class));
라고 적어서 이름을 잘못 적어서 예외가 발생하는 일이 없도록 할 수도 있다.
기존의 Bean을 재활용하는 방법
- 방법1. Bean 메서드를 직접 호출하기
@Bean
public Person person2MethodCall{
//name, age, address라는 bean을 사용하여 bean을 만듦.
return new Person(name(), age(), address());
}
- 방법2. Bean의 메서드를 호출하는 대신 매개 변수를 호출하기
@Bean
public Person person3Parameters (String name, int age, Address address2 ){
//name, age, address라는 bean을 사용하여 bean을 만듦.
return new Person(name, age, address2);
}
12단계 - Spring IOC 컨테이너 살펴보기 - 애플리케이션 컨텍스트 및 Bean Factory
스프링 컨테이너 (= IOC(제어의 역) 컨테이너)
스프링 Bean과 수명 주기 관리
빈 팩토리
메모리에 심한 제약이 있는 IOT의 경우 사용하는 것이다.
13단계 - Java Bean, POJO, Spring Bean 살펴보기
Q. Java Bean과 POJO, Spring Bean의 차이
-
EJB : Java Bean이라는 개념을 도입한 것. => 퍼블릭 기본 생성자, 게터와 세터의 존재, 인터페이스 Serializable(직렬화) 선언 => 중요하지 않음. 이를 사용하는 사람이 적음
-
POJO : 아무 제약 없는 모든 Java클래스!!!
-
Spring Bean
14단계 - Spring Framework Bean 자동 연결 살펴보기 - 기본 및 한정자
Q. Spring이 관리하는 Bean 프레임워크를 모두 나열하려면 어떻게 해야 하나
A. 컨텍스트를 요청해야 한다.
context.getBeanDefinitionNames : 정의된 모든 이름을 반환함.
context.getBeanDefinitionCount : 정의된 Bean 개수를 반환함.
context.getBeanDefinition : Bean의 이름을 매개 변수로 구문 분석함.
context.getBeanDefinitionNames
- 배열로 스트림을 만들기 : Arrays.stream(context.getBeanDefinitionNames)
- forEach문으로 스트림의 모든 요소를 sysout함
Arrays.stream(context.getBeanDefinitionNames).forEach(System.out::println);
- 결과 : helloWorldConfiguration, name, age, person, person2MethodCall, person3Parameters, address2, address3
즉, Spring이 관리하는 Bean 프레임워크를 모두 나열함.
@Primary
@Bean 아래에 어떤 후보가 가장 중요한지
@Qualifier : Bean 과 Bean 사이를 연결 시킴.
문제를 해결하는 옵션
ex) @Qualifier(“address3qualifier”) => address3qualifier를 객체 외부에서 사용이 가능해짐.
@Bean
public Person person5Qualifier(String name, int age, @Qualifier("address3qualifier")){
return new Person(name, age, address);
]
@Bean(name = " address3 ")
@Qualifier("address3qualifier")
public Address address3() {
return new Address("Montinagar", "Hyderabad" );
}
- System.out.println(context.getBean(“person5Qualifier”)) 로 값을 확인
15단계 - Spring Framework를 사용하여 Java 게이밍 앱의 Bean 관리
- 프라이빗 리소스
try (var context = new AnnotationConfigApplicationContext(HelloWorldConfiguration.class)) {
System.out.println(context.getBean("name"));
System.out.println(context.getBean("age"));
System.out.println(context.getBean("person"));
System.out.println(context.getBean("address"));
}
코드 내에서 예외가 발생하면 상황별 단서가 자동으로 호출
16단계 - Java Spring Framework 에 대한 많은 질문 - 학습할 내용
사람이 아닌, Spring이 객체를 만들도록 하려면 어떻게 해야 할까?