본문 바로가기
Spring/Spring Framework 시작하기

3. record 데이터 타입

by 김꾸꾸(하트) 2023. 5. 22.
<학습목표>
record데이터타입을 사용해 사용자 지정 객체를 더 만들고 Spring이 관리하도록 하기

record

정의

Java 14부터 도입된 새로운 데이터 타입,

데이터를 저장하고 접근하기 위한 간단한 클래스를 생성하는 데 사용함.

 

특징

  1. get/set메서드와 생성자, equals(), hashCode(), toString()등을 만들 필요가 없어짐.(모두 자동 생성됨)
  2. 주로 데이터 전달이나 저장에 사용됨
  3. 불변성과 간결성을 가짐

 

불변성이란?

객체의 상태가 생성 이후에 변경되지 않는 것

즉, 한 번 생성된 객체의 내부 상태는 변경될 수 없는 것을 의미

만약 변경한다면, 새로운 데이터로 간주함.

 

     실습      

1. 설정파일에서 Bean객체 만들기

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

//두 개의 메게변수가 있는 Person 생성자 자동으로 생성하기
record Person (String name , int age) {}; // 여기서 두 개의 멤버 변수인 name과 age를 정의함
record Address(String firstLine , String city) {};

@Configuration //Spring설정클래스, Spring bean을 정의하는 클래스
public class HelloWorldConfiguration {
	
	
	   //Bean은 Spring 컨테이너가 관리
		@Bean 
		public String name() {
			return "Ranga";
		}
		
		@Bean
		public int age() {
			return 15;
		}
		
		@Bean //record로 만든 Person생성자
		public Person person() {
			return new Person("라비" , 20);
		}
		
		@Bean
		public Address address() {
			return new Address("별내로100" , "경기도");
		}

}

 

 

 

2. Spring 컨텍스트를 실행하기

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class App02HelloWorldSpring {
	public static void main(String[] args) {
		
		//1. Spring컨텍스트 실행하기.
		var context = 
		new AnnotationConfigApplicationContext(HelloWorldConfiguration.class);
		
		
		/*2. Spring에서 관리할 항목 구성
		- HelloWorldConfiguration클래스 - @Configuration
		- name()메서드 - @Bean 
		*/
		
		
		//3. Spring에서 관리하는 Bean가져오기
		System.out.println(context.getBean("name"));
		System.out.println(context.getBean("age"));
		System.out.println(context.getBean("person"));
		System.out.println(context.getBean("address"));
		
		
	}

}