본문 바로가기

서버

Spring boot - Context Bean 생성하기 실습

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의 변수명 생성과는 조금 다르니 조심해야함.