๐Ÿ”ฎSpring

[Spring Boot] Application Context ์‚ฌ์šฉํ•˜๊ธฐ

harry.93 2022. 2. 2. 09:24
๋ฐ˜์‘ํ˜•

Application Context

์–ดํ”Œ๋ฆฌ์ผ€์ด์…˜ ๊ตฌ์„ฑ์— ๋Œ€ํ•œ ์ ‘๊ทผ์„ ๊ฐ€๋Šฅ์ผ€ ํ•˜๋Š” ์ธํ„ฐํŽ˜์ด์Šค (์„ค๋ช…)

 

Spring Boot ์—์„œ๋Š” ApplicationContextAware ๊ฐ€ ์‚ฌ์šฉ๋˜๋ฉฐ, ํ•ด๋‹น ์ธํ„ฐํŽ˜์ด์Šค๋Š” ApplicationContext์— ๋Œ€ํ•œ ์ •๋ณด๋ฅผ ๋ฐ›๊ณ ์ž ํ•˜๋Š” ๊ฐœ์ฒด์— ์˜ํ•ด ๊ตฌํ˜„๋œ๋‹ค. ์ง€๊ธˆ ์‚ดํŽด๋ณด๊ณ ์ž ํ•˜๋Š” ๊ฒƒ์€, Beans์— ์•ก์„ธ์Šค ํ•˜์—ฌ ํŠน์ • Bean์„ get ๋˜๋Š” set ํ•˜๊ธฐ ์œ„ํ•œ ๋ฐฉ๋ฒ•์ด๋‹ค.

package helloworld;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import org.springframework.stereotype.Component;

@Component
public class Beans implements ApplicationContextAware {
	private static ApplicationContext applicationContext = null;
    
	public static ApplicationContext getApplicationContext() {
		return applicationContext;
	}
    
	public static GenericApplicationContext getGenericContext() {
		return (GenericXmlApplicationContext) applicationContext;
	}

	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.applicationContext = applicationContext;
	}

}

 

์œ„ ์ฝ”๋“œ๋ฅผ ํ†ตํ•ด ApplicationContext๋ฅผ ๊ฐ€์ ธ์˜ฌ ์ˆ˜ ์žˆ์œผ๋ฉฐ, ๋นˆ์— ์•ก์„ธ์Šค ํ•  ์ˆ˜ ์žˆ๊ฒŒ๋œ๋‹ค. 

getApplicationContext().getBean() ์„ ํ†ตํ•ด ์›ํ•˜๋Š” ๊ณณ์—์„œ ๋นˆ์„ ๊ฐ€์ ธ์™€ ์‚ฌ์šฉํ•œ๋‹ค.

 

** Spring ๊ตฌ๋™ ์‹œ, ApplicationContextAware ๊ตฌํ˜„์ด ๋ฐœ๊ฒฌ๋˜๋ฉด setApplicationContext๋ฅผ ์‹คํ–‰ํ•œ๋‹ค.


์ฐธ๊ณ 

https://stackoverflow.com/questions/34088780/how-to-get-bean-using-application-context-in-spring-boot

 

How to get bean using application context in spring boot

I am developing a SpringBoot project and I want to get the bean by its name using applicationContext. I have tried many solution from web but could not succeed. My Requirement is that I have a cont...

stackoverflow.com

 

728x90
๋ฐ˜์‘ํ˜•