스프링 빈을 등록하는 방법에는 여러가지 방법이 있다.
아래는 그 예들이다.
import org.springframework.stereotype.Component;
@Component
public class MyComponent {
public void hello() {
}
}
@Component로 등록을 하게 되면 @Springbootapplication이 자동으로 @Componentscan을 통해 빈으로 등록한다.
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MyConfiguration {
@Bean
public MyBean myBean() {
return new MyBean();
}
@Bean
public AnotherBean anotherBean() {
return new AnotherBean(myBean());
}
}
직접 빈으로 등록하는 방법으로 @Configuration을 통해 설정 파일로 등록하고 나서 @Bean을 통해 직접 빈으로 등록한다. 이 때 @Configruation을 통해 자동으로 스프링 부트가 설정파일로 인식 한다.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="myBean" class="com.example.MyBean"/>
<bean id="anotherBean" class="com.example.AnotherBean">
<constructor-arg ref="myBean"/>
</bean>
</beans>
xml로 등록하는 방법도 있다.
많이 사용해 보지 않아 익숙하지 않다.
이 어노테이션들에는 자동으로 @Component가 들어 있어 빈으로 등록이 된다. 각자 쓰임에 맞는 곳에 알맞게 사용하면 된다.