@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 "";
}
'웹 개발 > Spring' 카테고리의 다른 글
[Spring] JPA - How to fix “Error executing DDL ”alter table events drop foreign key {foreign key} “ via JDBC Statement” (0) | 2021.03.12 |
---|---|
[Spring] JPA - @OneToOne 조인 전략을 left join -> inner join 으로 변경하기 (0) | 2021.03.12 |
[Spring] JPA - Could not write JSON: Infinite recursion (StackOverflowError) (0) | 2021.03.11 |
[Spring] Spring REST Docs 호스트 변경 (0) | 2021.03.04 |
[Spring] 웹 애플리케이션 구조 (0) | 2020.09.10 |