@Bean

코딩냥이·2024년 9월 10일

Annotation

목록 보기
11/34

@Bean

@Bean은 스프링 프레임워크에서 개발자가 직접 제어가 불가능한 외부 라이브러리 등을 Bean으로 등록하고자 할 때 사용하는 어노테이션입니다.

기능

  • 메소드가 Spring 컨테이너에 의해 관리되는 Bean을 생성함을 나타냅니다.
  • 주로 @Configuration 어노테이션이 적용된 클래스의 메소드에 사용됩니다.
  • 개발자가 직접 인스턴스를 생성하고 세부적으로 설정할 수 있게 해줍니다.

사용 방법

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class AppConfig {

    @Bean
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/mydb");
        dataSource.setUsername("user");
        dataSource.setPassword("password");
        return dataSource;
    }

    @Bean
    public UserService userService(UserRepository userRepository) {
        return new UserServiceImpl(userRepository);
    }
}

주요 특징

  1. 명시적 빈 등록: 개발자가 빈의 생성과 설정을 직접 제어할 수 있습니다.
  2. 메소드 이름 = 빈 이름: 기본적으로 메소드 이름이 빈의 이름이 됩니다.
  3. 의존성 주입: 메소드 파라미터를 통해 다른 빈을 주입받을 수 있습니다.
  4. 생명주기 콜백: 초기화 및 소멸 메소드를 지정할 수 있습니다.

@Bean vs @Component

  • @Bean: 개발자가 제어하지 못하는 외부 라이브러리를 빈으로 등록할 때 주로 사용합니다.
  • @Component: 개발자가 직접 작성한 클래스를 빈으로 등록할 때 사용합니다.
// @Bean 사용 예
@Configuration
public class AppConfig {
    @Bean
    public ThirdPartyService thirdPartyService() {
        return new ThirdPartyService();
    }
}

// @Component 사용 예
@Component
public class MyService {
    // ...
}

빈 이름 지정

기본적으로 메소드 이름이 빈 이름이 되지만, 직접 지정할 수도 있습니다:

@Bean(name = "mySpecialDataSource")
public DataSource dataSource() {
    // ...
}

의존성 주입

@Bean 메소드는 다른 빈을 파라미터로 받아 의존성을 주입할 수 있습니다:

@Bean
public UserService userService(UserRepository userRepository, EmailService emailService) {
    return new UserServiceImpl(userRepository, emailService);
}

생명주기 콜백

빈의 초기화와 소멸 시 호출될 메소드를 지정할 수 있습니다:

@Bean(initMethod = "init", destroyMethod = "cleanup")
public DatabaseConnection databaseConnection() {
    return new DatabaseConnection();
}

조건부 빈 등록

@Conditional 어노테이션과 함께 사용하여 조건부로 빈을 등록할 수 있습니다:

@Bean
@Conditional(DataSourceCondition.class)
public DataSource dataSource() {
    // ...
}

빈 스코프 지정

@Scope 어노테이션을 사용하여 빈의 스코프를 지정할 수 있습니다:

@Bean
@Scope("prototype")
public PrototypeBean prototypeBean() {
    return new PrototypeBean();
}

테스트

@Bean으로 등록된 빈을 테스트할 때는 주로 @Configuration 클래스를 import하여 사용합니다:

@SpringBootTest
@Import(AppConfig.class)
class DataSourceTest {

    @Autowired
    private DataSource dataSource;

    @Test
    void testDataSourceConfiguration() {
        assertNotNull(dataSource);
        // 추가 검증 로직
    }
}

베스트 프랙티스

  1. 적절한 사용: 외부 라이브러리 등 직접 제어할 수 없는 클래스를 빈으로 등록할 때 사용하세요.
  2. 명확한 이름 지정: 빈의 역할을 명확히 나타내는 이름을 사용하세요.
  3. 적절한 위치: 관련 있는 빈들을 하나의 @Configuration 클래스에 모아 관리하세요.
  4. 의존성 주입 활용: 생성자 주입을 통해 필요한 의존성을 명확히 표현하세요.
  5. 단일 책임 원칙: 각 @Bean 메소드가 단일 책임을 가지도록 설계하세요.

결론

@Bean 어노테이션은 스프링의 IoC 컨테이너에 의해 관리될 객체를 직접 정의하고 구성할 수 있게 해주는 강력한 도구입니다. 이를 통해 개발자는 외부 라이브러리나 복잡한 설정이 필요한 객체를 스프링의 관리 하에 둘 수 있으며, 애플리케이션의 구성을 보다 유연하고 세밀하게 제어할 수 있습니다.

연관 포스팅

@Configuration
@Component
@Autowired
@Scope
@Conditional

profile
HelloMeow~!

0개의 댓글