Java 14부터 도입된 Record 클래스는 불변 데이터를 객체 간에 전달하는 작업을 간단하게 만들어준다. Record 클래스를 사용하면 불필요한 코드를 제거할 수 있고, 적은 코드로도 명확한 의도를 표현할 수 있다라고 합니다.
Record의 특징으로는
- 멤버변수는 private final로 선언된다
- 필드별 getter가 자동으로 생성된다
- 모든 멤버변수를 인자로 하는 public 생성자를 자동으로 생성한다
—> (@allargsconstructor와 유사하지만, record는 불변 데이터를 다루므로 생성자가 실행될 때 인스턴트 필드를 수정할 수 없다) - equals, hashcode, toString을 자동으로 생성한다
- 기본생성자는 제공하지 않으므로 필요한 경우 직접 생성해야 한다
HelloWorldConfiguration.java
package com.in28minutes.learnspirngframework;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
//Eliminate verbosity in creating Java Beans
//Public accessor methods, constructor
//equals, hashcode and toString are automatically created.
//Released in JDK 16
record Person(String name, int age) {};
//Address - firstLine & city
record Address(String firstLine, String sity) {};
@Configuration
public class HelloWorldConfiguration {
@Bean
public String name() {
return "Range";
}
@Bean
public int age() {
return 35;
}
@Bean
public Person person() {
return new Person("choi", 35);
}
@Bean
public Address address() {
return new Address("Kim", "Seoul");
}
App02HelloWorldSpring.java
package com.in28minutes.learnspirngframework;
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 - @Configuration
// HelloWorldConfiguration - @Configuration
//name - @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"));
}
}
'JAVA' 카테고리의 다른 글
회원관리 프로그램 작성하기 (0) | 2023.09.07 |
---|---|
채팅 프로그램 만들어보기 (0) | 2023.09.07 |
네트워크 프로그래밍 - 2 (0) | 2023.09.07 |
네트워크 프로그래밍 - 1 (0) | 2023.09.05 |
쓰레드(Thread) 개념, 실행방법 (0) | 2023.09.05 |
댓글