스프링에서의 빈(bean) 등록은 애플리케이션에서 사용할 객체를 스프링 컨테이너가 관리할 수 있도록 등록하는 과정입니다. 빈은 스프링 컨테이너에 의해 생성되고, 필요할 때 주입되며, 생명주기를 관리받습니다.
스프링에서 빈을 등록하는 방법은 크게 세 가지로 나눌 수 있습니다.
클래스에 @Component(또는 파생 어노테이션)를 사용하고, 해당 클래스가 컴포넌트 스캔 경로에 포함되면 자동으로 빈으로 등록됩니다.
주요 어노테이션:
@Component
public class MyService {
public void doSomething() {
System.out.println("Doing something...");
}
}
@ComponentScan은 @SpringBootApplication에 포함되어 있다
@SpringBootApplication
public class MyApp {
public static void main(String[] args) {
SpringApplication.run(MyApp.class, args);
}
}
@Configuration이 붙은 클래스 내에서 @Bean 메서드를 사용하여 직접 빈을 정의하고 등록합니다.
@Configuration
public class AppConfig {
@Bean
public MyService myService() {
return new MyService();
}
}
XML 파일에 태그를 사용해 빈을 등록합니다. 이는 과거 방식으로, 현재는 잘 사용되지 않습니다.
<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="myService" class="com.example.MyService" /> </beans>
스프링 빈은 기본적으로 싱글톤(singleton) 스코프로 등록되지만, 다른 스코프도 지원합니다.
@Bean
@Scope("prototype")
public MyService myService() {
return new MyService();
}
등록된 빈은 스프링의 의존성 주입(DI) 메커니즘에 의해 다른 빈에서 사용될 수 있습니다.
주요 주입 방법:
@Service
public class MyController {
private final MyService myService;
public MyController(MyService myService) {
this.myService = myService;
}
}
@Service
public class MyController {
@Autowired
private MyService myService;
}
@Service
public class MyController {
private MyService myService;
@Autowired
public void setMyService(MyService myService) {
this.myService = myService;
}
}
컨테이너에서 빈을 조회하려면 ApplicationContext를 사용합니다.
@SpringBootApplication
public class MyApp {
public static void main(String[] args) {
ApplicationContext context = SpringApplication.run(MyApp.class, args);
MyService myService = context.getBean(MyService.class);
myService.doSomething();
}
}
일반적인 애플리케이션 클래스는 @Component를 사용하여 간단하게 등록하고, 특수한 객체 생성 로직이나 외부 클래스는 @Bean으로 처리합니다.
