Notice
Recent Posts
Recent Comments
Link
SeouliteLab
[Java/자바] Spring @Bean: 빈으로 등록하기 본문
Spring 프레임워크에서 @Bean 어노테이션은 개발자가 직접 스프링 빈을 등록할 때 사용됩니다. 이 글에서는 @Bean 어노테이션의 사용법과 예제 코드를 통해 자세히 알아보겠습니다.
1. 기본적인 @Bean 사용법
가장 간단한 형태의 @Bean 어노테이션은 다음과 같이 메서드에 붙여서 사용합니다.
package com.example.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AppConfig {
@Bean
public MyBean myBean() {
return new MyBean();
}
}
위의 예제에서 myBean
메서드는 MyBean
클래스의 인스턴스를 스프링 빈으로 등록합니다.
2. 빈 생성 시 의존성 주입하기
@Bean 어노테이션을 사용하여 빈을 생성할 때 다른 빈을 주입할 수 있습니다. 다음은 예제 코드입니다.
예제 1: 의존성 주입하기
package com.example.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AppConfig {
@Bean
public AnotherBean anotherBean() {
return new AnotherBean();
}
@Bean
public MyBean myBean() {
return new MyBean(anotherBean());
}
}
위의 예제에서 myBean
메서드는 AnotherBean
클래스의 인스턴스를 생성자를 통해 주입받아 MyBean
클래스의 인스턴스를 생성합니다.
3. 예제 코드
다음은 @Bean 어노테이션을 사용한 예제 코드입니다.
예제 1: 기본적인 @Bean 사용법
package com.example.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AppConfig {
@Bean
public MyBean myBean() {
return new MyBean();
}
}
예제 2: 빈 생성 시 의존성 주입하기
package com.example.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AppConfig {
@Bean
public AnotherBean anotherBean() {
return new AnotherBean();
}
@Bean
public MyBean myBean() {
return new MyBean(anotherBean());
}
}
4. 결론
이상으로 Spring의 @Bean 어노테이션에 대한 자세한 설명과 예제 코드를 살펴보았습니다. @Bean 어노테이션을 사용하여 스프링 애플리케이션을 구성할 때 유용하게 활용할 수 있습니다.
해시태그:
'프로그래밍' 카테고리의 다른 글
[Java/자바] Spring @ExceptionHandler: 예외 처리하기 (0) | 2024.03.12 |
---|---|
[Java/자바] Spring @RequestHeader: HTTP 요청 헤더 처리 (0) | 2024.03.12 |
[Java/자바] Spring @Configuration: 설정 클래스로 애플리케이션 구성하기 (0) | 2024.03.12 |
[Java/자바] Spring @Component에 대한 자세한 설명과 예제 (0) | 2024.03.12 |
Java의 getOrDefault() 메서드 이해하기 (0) | 2024.03.11 |