본문 바로가기
F::d

@Bean, @Configuration 그리고 @Component

by 아임제니퍼 2025. 1. 2.

@Configuration

Indicates that a class declares one or more @Bean methods and may be processed by the Spring container to generate bean definitions and service requests for those beans at runtime
 @Configuration
 public class AppConfig {
     @Bean
     public MyBean myBean() {
         // instantiate, configure and return bean ...
     }
 }

@Component

Indicates that the annotated class is a component.
Such classes are considered as candidates for auto-detection when using annotation-based configuration and classpath scanning.
A component may optionally specify a logical component name via the value attribute of this annotation.

 

Configuration + Bean과 Component 어노테이션이 사용되면 모두 스프링의 IoC 컨테이너에 객체로 관리되며 어플리케이션 전역적으로 의존성 주입에 활용될 수 있다.

 

BeanComponent 차이

선언 위치 차이

 

Component는 class level에 선언되고 Bean은 메소드 레벨에 선언된다. 패스워드 암호화를 위해 Bcrypt를 사용하는 모듈을 각각의 방식으로 표현하면 이렇다.

@Configuration
@EnableWebSecurity
public class SecurityConfig {
    @Bean
    public PasswordEncoder getPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }
}
@Component
public class PasswordEncoder {
    public String encode(String seed) {
        return new BCryptPasswordEncoder().encode(seed);
    }

    public boolean matches(String seed, String password) {
        return new BCryptPasswordEncoder().matches(seed, password);
    }
}

 

사용법의 차이

 

Bean외부 라이브러리가 제공하는 객체를 사용할 때 활용하고 Component는 내부에서 직접 접근 가능한 클래스를 사용하면 된다.

 

@Component
public class PasswordEncoder {
    public String encode(String seed) {
        return new BCryptPasswordEncoder().encode(seed);
    }

    public boolean matches(String seed, String password) {
        return new BCryptPasswordEncoder().matches(seed, password);
    }
}

 

위 코드에서 Component 어노테이션을 쓸 수 있는 이유는 PasswordEncoder라는 class를 직접 만들었기 때문이다. 만약 이 코드가 라이브러리에 있는 코드라면 나는 이 클래스에 Component를 추가할 수 없다. 따라서 라이브러리에 있는 객체를 사용할 때는 Bean을 활용할 수 있다.

 

 

Bean과 Configuration

 

Bean을 사용시 Configuration 어노테이션을 꼭 사용해야 한다.  Bean만 선언했을 경우, 이 Bean을 다른 곳에서 의존성 주입하는데 활용할 수 없다.

 

<참고>
What is the difference between @Configuration and @Component in Spring?
https://stackoverflow.com/questions/39174669/what-is-the-difference-between-configuration-and-component-in-spring

https://docs.spring.io/spring-framework/docs/4.0.4.RELEASE/javadoc-api/org/springframework/context/annotation/Configuration.html

https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/stereotype/Component.html

Bean과 Component 차이
https://medium.com/sjk5766/bean%EA%B3%BC-component-%EC%B0%A8%EC%9D%B4-96a8d0533bfd