Spring Boot

Spring Boot Bean 등록 방법 5가지

iksadnorth 2023. 7. 29. 16:44

1. resources/application.xml 작성

매우 원시적인 방법으로 Bean으로 등록할 클래스를 작성한 후에,
다음과 같이 application.xml에서 Bean으로 등록함.

더보기
<?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="userService" class="com.example.UserService">
        <!-- 빈에 프로퍼티 설정 예시 (옵션) -->
        <property name="userRepository" ref="userRepository"/>
    </bean>
    
    <bean id="userRepository" class="com.example.UserRepository"/>
</beans>
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {
    public static void main(String[] args) {
        // 스프링 컨테이너를 생성하고 XML 설정 파일을 로드합니다.
        ApplicationContext context = new ClassPathXmlApplicationContext("application.xml");

        // 등록된 Bean을 가져옵니다.
        // @Autowired 가 없으니 이런 방식으로 주입해야 함.
        UserService userService = context.getBean(UserService.class);

        // UserService의 메서드를 호출합니다.
        String message = userService.sayHello("John");
        System.out.println(message);
    }
}

 

2. resources/application.xml, component-scan 

1번과 다르게 Java Annotation을 이용해서 자바 코드 내에서 Bean 정의.
대신 어떤 Root Directory에서 부터 Bean Component를 찾을지에 대한 내용을 
application.xml에서 정의해야 함.
정의한 경로를 기준으로 하위 디렉토리의 클래스 중 @Component가 붙어있는 클래스를 Bean으로 등록.

더보기
<?xml version="1.0" encoding="UTF-8"?>
<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 https://www.springframework.org/schema/context/spring-context.xsd">
    
    <!-- 여기서 Component Scan 위치를 정의 -->
    <context:component-scan base-package="com.example.project" />
    
</beans>
// BookRepository.java
package com.example.project.repository;

import org.springframework.stereotype.Repository;

@Repository
public class BookRepository {
}

// BookService.java
package com.example.project.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class BookService {

    @Autowired
    BookRepository bookRepository;

    public void setBookRepository(BookRepository bookRepository) {
        this.bookRepository = bookRepository;
    }
}

 

3. Java Config 작성.

1번 방법의 Java 코드 버전이라고 생각하면 된다.
Config 클래스에서 각 Bean으로 등록할 클래스들을 생성하고
해당 Config 클래스를 AnnotationConfigApplicationContext에 등록함.

더보기
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ApplicationConfig {

    @Bean
    public BookRepository bookRepository() {
        return new BookRepository();
    }

    @Bean
    public BookService bookService(BookRepository bookRepository) {
        BookService bookService = new BookService();

        // 의존성 주입 setter 이용
        bookService.setBookRepository(bookRepository);
        return bookService;
    }
}
public class DemoApplication {

    public static void main(String[] args) {
        // 직접 ApplicationConfig.java 클래스를 등록함.
        ApplicationContext context = new AnnotationConfigApplicationContext(ApplicationConfig.class);
    }

}

 

4. Java Config, ComponentScan

2번 방법의 Java 코드 버전이라고 생각하면 된다.
어떤 Root Directory에서 부터 Bean Component를 찾을지에 대한 내용을 
@ComponentScan 속성을 이용해서 정의함.

더보기
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan(basePackageClasses = SpringApplication.class) // 최상단 메인 클래스
public class ApplicationConfig {
}

5. Spring Boot

4번 방식을 미리 세팅한 Annotation을 이용.
@SpringBootApplication 자체가 @ComponentScan 어노테이션을 내포하고 있기 때문에 해당 어노테이션을 기준으로 하위 디렉토리의 @Compoent 가 붙은 클래스를 모두 @Bean으로 등록한다.

더보기
@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

'Spring Boot' 카테고리의 다른 글

SpEL - Spring Expression Language  (0) 2023.07.29
Spring Boot AOP  (0) 2023.07.29
Spring Logging System  (0) 2023.07.29
Spring Boot 외부 설정법  (0) 2023.07.28
Spring Boot HTTP2 적용  (0) 2023.07.28