728x90
개요: Context의 생태계를 확인하기 위해 실습을 해본다.
package com.in28minutes.learn_spring_framework;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
record Person(String name, int age, Address address) {};
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("tomhoon", 30, new Address("Main Street", "Utah"));
}
@Bean(name = "address")
public Address address() {
return new Address("Basic Street", "Busan");
}
@Bean(name = "address2")
public Address addressTwo() {
return new Address("bakerStreet", "Anyang");
}
@Bean(name = "address3")
public Address addressThree() {
return new Address("Gumchen Street", "Seoul");
}
@Bean
public Person person2MethodCall() {
return new Person(name(), age(), address());
}
@Bean
public Person person3Parameters(String name, int age, Address address3) {
return new Person(name, age, address3);
}
}
제일 위
record Person을 보면 파라미터가 3개다
String, int, Address 타입으로 구성되어 있다.
Address를 제공해주는 Bean은 3가지다
1) public Address address()
2) public Address addressTwo() -> 빈 이름은 address2
3) public Address addressThree() -> 빈 이름은 address3
person3Parameters 메소드를 보면
파라미터 중 Address 타입을 변수명으로 address3로 되어있다.
이것은 Bean 이름이며 일반적인 변수명이 아니다.
메인 스레드에서 확인해보자
package com.in28minutes.learn_spring_framework;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class App02HelloWorldSpring {
public static void main(String[] args) {
var context = new AnnotationConfigApplicationContext(HelloWorldConfiguration.class);
String name = (String)context.getBean("name");
System.out.println(name);
System.out.println(context.getBean("person"));
System.out.println(context.getBean("address2"));
// System.out.println(context.getBean(Address.class));
System.out.println(context.getBean("person2MethodCall"));
System.out.println(context.getBean("person3Parameters"));
}
}
Address 필드값에
Gumchen Street, Seoul로 되어있다.
다시
SpringContext의
person3Parameters 메소드가 리턴해주는 Bean을 살펴보자
변수명은
Spring Context 안에 있는
Bean의 이름으로 잡힌다.
기존 Java의 변수명 생성과는 조금 다르니 조심해야함.
'서버' 카테고리의 다른 글
Java - 반복해서 문구 생성해야 할 때 java로 프로그램 만들기 (0) | 2024.08.28 |
---|---|
SpringBoot에서 서버를 켰을 때 compile 에러가 나는 경우 (1) | 2024.08.23 |
Springboot - context의 bean 생성시 기존 메소드 사용하기 (0) | 2024.08.22 |
Springboot - record 사용해보기 (0) | 2024.08.22 |
Springboot - Spring Context 다루기 (0) | 2024.08.22 |