본문 바로가기

웹 개발/Spring

[Spring] @Bean와 @Component의 차이

@Bean의 경우 개발자가 컨트롤이 불가능한 외부 라이브러리들을 Bean으로 등록하고 싶은 경우에 사용된다. 

 

예를 들어, 다음과 같이 사용할 수 있다.

    @Bean
    public ObjectMapper objectMapper() {
        ObjectMapper objectMapper = new ObjectMapper();
        return objectMapper;
    }

 

애노테이션 내부를 보면 @Target이 METHOD, ANNOTATION_TYPE으로 되어 있다.

@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Bean {
    @AliasFor("name")
    String[] value() default {};

    @AliasFor("value")
    String[] name() default {};

    /** @deprecated */
    @Deprecated
    Autowire autowire() default Autowire.NO;

    boolean autowireCandidate() default true;

    String initMethod() default "";

    String destroyMethod() default "(inferred)";
}

 

 

 

 

 

반대로,  개발자가 직접 컨트롤이 가능한 Class들의 경우엔 @Component를 사용한다.

 

예를 들어, 다음과 같이 사용할 수 있다.

 

@Component
@ConfigurationProperties(prefix = "app")
@Getter @Setter
public class AppProperties {

    @NotEmpty
    private String adminUsername;

    @NotEmpty
    private String adminPassword;

    @NotEmpty
    private String clientId;

    @NotEmpty
    private String clientSecret;

}

 

애노테이션 내부를 보면 @Target이 TYPE으로 되어 있다.

 

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Indexed
public @interface Component {
    String value() default "";
}