hrming

[Spring] bean 등록 방법 & @Configuration 본문

Spring

[Spring] bean 등록 방법 & @Configuration

hrming 2025. 2. 8. 16:45

■ @Component 어노테이션 기반 등록

Spring이 자동으로 Bean을 감지하고 등록할 수 있도록 @Component 및 관련 어노테이션을 사용함

 

- @Component 사용

- @Service, @Repository, @Controller 사용

구분 용도
@Service 서비스 계층 클래스에 사용
@Repository DAO(데이터 엑세스) 계층 클래스에 사용
@Controller Spring MVC 컨트롤러에 사용

 

import org.springframework.stereotype.Component;

@Component  // 자동으로 Spring Bean으로 등록됨
public class MyComponent {
    public void hello() {
        System.out.println("Hello, Spring Bean!");
    }
}
import org.springframework.stereotype.Service;

@Service
public class MyService {
    public String getMessage() {
        return "Hello from MyService!";
    }
}

 

- 자동 등록을 활성화하려면 @ComponentScan 추가 혹은 XML 설정해야 함 🌟 

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan(basePackages = "com.example") // 지정한 패키지 내 @Component 자동 탐색
public class AppConfig {
}
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context.xsd">

    <!-- @Component, @Service, @Repository 등을 자동 스캔 -->
    <context:component-scan base-package="com.example"/>

</beans>

 

■ Java Config 기반 수동 등록 (@Bean 사용)

직접 Java Config 클래스에서 @Bean을 이용해 등록하는 방식

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class AppConfig {
    
    @Bean
    public MyService myService() {
        return new MyService();
    }
}
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Main {
    public static void main(String[] args) {
        ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
        MyService myService = context.getBean(MyService.class);
        System.out.println(myService.getMessage());
    }
}

 


 

■ XML 기반 등록 (beans.xml 활용)

Spring의 beans.xml 파일을 사용하여 Bean을 등록하는 방식

 

- beans.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>

 

- XML 설정을 이용한 ApplicationContext 로드 

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        MyService myService = (MyService) context.getBean("myService");
        System.out.println(myService.getMessage());
    }
}

 

 


✏️ 정리

등록 방식 사용 방법 특징
@Component 기반 @Component @Service, @Repository, @Controller 빈 자동 등록
@Bean 기반 @Configuration 클래스에서 @Bean 메서드 등록 빈 수동 등록, 커스터마이징 유리
XML 기반 beans.xml에서 <bean> 태그 사용 과거 방식, 설정이 복잡

 


 

■ @Configuration

: 위에서 확인했듯이, @Component 기반이나, @Bean 기반 빈 등록 시, @Configuration을 사용하게 된다.

: @Configuration 내부를 보면, @Component가 추가되어있다. 따라서 해당 클래스 또한 빈으로 등록된다. 이후, 해당 클래스의 본문을 파싱해서 @Bean이 붙어있는 메서드를 찾아서 빈을 생성해준다.

: @Configuration은 빈을 등록할 때, 싱글톤이 되도록 보장해줌. ( @Bean만으로도 빈 등록을 할 수 있지만, 이 경우에는 싱글톤이 유지되지 않는다.)

 


참고 및 출처 

https://youwjune.tistory.com/43

 

[Spring] 스프링에서 빈 객체를 등록하는 방법(@Bean, @Component)

https://youwjune.tistory.com/37 [Spring] DI와 IOC에 대해서 스프링을 막 공부하기 시작하는 비기너에게 DI와 IOC에 대한 개념은 너무나도 중요한 것 같습니다! 하지만, 이를 왜 사용할까요? DI와 IOC를 활용하

youwjune.tistory.com

 

https://fvor001.tistory.com/27

 

[Spring] component-scan 사용이유

component-scan이란? 빈(Bean)으로 등록될 준비가 된 클래스들을 스캔하여 빈(Bean)으로 등록해준다. 빈(Bean)으로 등록될 준비가 된 클래스들이란? @Component, @Controller, @Service, @Repository 어노테이션을 붙인

fvor001.tistory.com

 

https://idkim97.github.io/2023-07-11-%EC%BB%B4%ED%8F%AC%EB%84%8C%ED%8A%B8%20%EC%8A%A4%EC%BA%94(@ComponentScan)/

 

[스프링] 컴포넌트 스캔(ComponentScan)

 

idkim97.github.io

 

https://blogshine.tistory.com/551

 

[Spring] @Configuration 이란?

이번 글에서는 @Configuration을 사용하는 이점에 대하여 정리해볼까 한다. 1. @Configuration 이란? " data-ke-type="html"> HTML 삽입 미리보기할 수 없는 소스 Spring에서 Bean을 수동으로 등록하기 위해서는, 설

blogshine.tistory.com

 

ChatGPT

 

Comments