봄 @Configuration 주석은 스프링 코어 프레임워크의 일부입니다. 스프링 구성 주석은 클래스에 @Bean 정의 메서드가 있다는 것을 나타냅니다. 따라서 스프링 컨테이너는 클래스를 처리하고 응용 프로그램에서 사용할 수 있는 스프링 빈을 생성할 수 있습니다.
스프링 @Configuration
스프링 @Configuration 주석을 사용하면 의존성 주입에 주석을 사용할 수 있습니다. 이제 스프링 구성 클래스를 만드는 방법을 알아봅시다. 간단한 자바 빈 클래스를 만들어 보겠습니다.
package com.journaldev.spring;
public class MyBean {
public MyBean() {
System.out.println("MyBean instance created");
}
}
스프링 프레임워크 클래스를 사용하기 전에 Maven 프로젝트에 종속성을 추가해야 합니다.
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.6.RELEASE</version>
</dependency>
이제 스프링 구성 클래스를 만들어 보겠습니다.
package com.journaldev.spring;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MyConfiguration {
@Bean
public MyBean myBean() {
return new MyBean();
}
}
간단한 클래스를 작성하고 간단한 스프링 구성 클래스를 구성해 보겠습니다.
package com.journaldev.spring;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class MySpringApp {
public static void main(String[] args) {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(MyConfiguration.class);
ctx.refresh();
// MyBean mb1 = ctx.getBean(MyBean.class);
// MyBean mb2 = ctx.getBean(MyBean.class);
ctx.close();
}
}
위의 응용 프로그램을 실행하면 다음과 같은 출력이 생성됩니다:
May 23, 2018 12:34:54 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@ff5b51f: startup date [Wed May 23 12:34:54 IST 2018]; root of context hierarchy
MyBean instance created
May 23, 2018 12:34:54 PM org.springframework.context.support.AbstractApplicationContext doClose
INFO: Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@ff5b51f: startup date [Wed May 23 12:34:54 IST 2018]; root of context hierarchy
주의하세요. 스프링은 우리가 요청하기도 전에 빈을 컨텍스트에 로드합니다. 이는 모든 빈이 올바르게 구성되어 있고 어떤 문제가 발생하면 응용 프로그램이 빠르게 실패하는 것을 보장하기 위한 것입니다. 또한 ctx.refresh()
를 호출해야 합니다. 그렇지 않으면 컨텍스트에서 어떤 빈을 가져 오려고 할 때 다음 오류가 발생합니다.
Exception in thread "main" java.lang.IllegalStateException: org.springframework.context.annotation.AnnotationConfigApplicationContext@f0f2775 has not been refreshed yet
at org.springframework.context.support.AbstractApplicationContext.assertBeanFactoryActive(AbstractApplicationContext.java:1076)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1106)
at com.journaldev.spring.MySpringApp.main(MySpringApp.java:11)
내가 MyBean 인스턴스를 가져 오는 곳의 문을 해제하면 MyBean의 생성자가 호출되지 않는 것을 알 수 있습니다. 이것은 스프링 빈의 기본 범위가 싱글톤이기 때문입니다. 우리는 @Scope
주석을 사용하여 이를 변경할 수 있습니다.
만약 @Configuration 주석을 해제한다면?
MyConfiguration 클래스에서 @Configuration 주석을 제거하면 어떻게 될까요. 여전히 예상대로 작동하고 스프링 빈이 싱글톤 클래스로 등록되고 검색됩니다. 그러나 이 경우 myBean()
메서드를 호출하면 일반적인 자바 메서드 호출이 되어 MyBean의 새 인스턴스를 얻게 됩니다. 이를 증명하기 위해 MyBean 인스턴스를 사용하는 또 다른 빈을 정의해 보겠습니다.
package com.journaldev.spring;
public class MyBeanConsumer {
public MyBeanConsumer(MyBean myBean) {
System.out.println("MyBeanConsumer created");
System.out.println("myBean hashcode = "+myBean.hashCode());
}
}
우리의 업데이트된 스프링 구성 클래스는:
package com.journaldev.spring;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
//@Configuration
public class MyConfiguration {
@Bean
public MyBean myBean() {
return new MyBean();
}
@Bean
public MyBeanConsumer myBeanConsumer() {
return new MyBeanConsumer(myBean());
}
}
지금 MySpringApp
클래스를 실행하면 다음 출력이 생성됩니다.
MyBean instance created
MyBean instance created
MyBeanConsumer created
myBean hashcode = 1647766367
따라서 MyBean은 더 이상 싱글톤이 아니며, 이제 다시 @Configuration
어노테이션으로 MyConfiguration
을 주석 처리하고 MySpringApp
클래스를 실행합니다. 이번에는 출력이 아래와 같이 될 것입니다.
MyBean instance created
MyBeanConsumer created
myBean hashcode = 1095088856
따라서 우리가 원하는대로 스프링 컨테이너가 작동하는지 확인하려면 구성 클래스에 @Configuration
어노테이션을 사용하는 것이 좋습니다. 일부 이유로 @Configuration 어노테이션을 사용하고 싶지 않다면 myBean()
메소드를 호출하지 않고 @Autowired 어노테이션을 통해 구성된 MyBean의 인스턴스 변수를 사용하여 구성 클래스를 여전히 생성할 수 있습니다. 아래 코드처럼 작동할 것입니다.
package com.journaldev.spring;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
//@Configuration
public class MyConfiguration {
@Autowired
MyBean myBean;
@Bean
public MyBean myBean() {
return new MyBean();
}
@Bean
public MyBeanConsumer myBeanConsumer() {
return new MyBeanConsumer(myBean);
}
}
이것으로 스프링 구성 어노테이션에 대한 설명이 모두입니다. 앞으로의 포스트에서 다른 스프링 어노테이션을 살펴볼 것입니다.
예제 코드를 우리의 GitHub 저장소에서 다운로드할 수 있습니다.
Source:
https://www.digitalocean.com/community/tutorials/spring-configuration-annotation