프로그래밍 공부

Spring 및 Bean 설정 본문

Programming/Spring

Spring 및 Bean 설정

khj1999 2025. 2. 6. 20:45

Java Spring 및 Bean 설정 방법 정리

1. Spring Framework 개요

  • IoC(Inversion of Control): 객체 생성/관리를 프레임워크가 담당
  • DI(Dependency Injection): 객체 간 의존 관계를 설정하는 기술

2. Spring Bean 이란?

  • Spring 컨테이너가 관리하는 Java 객체
  • 애플리케이션의 핵심 구성 요소

3. Bean 설정 방법 3가지

3.1 XML 기반 설정 (전통적 방식)

<!-- applicationContext.xml -->
<beans>
    <bean id="userService" class="com.example.UserServiceImpl">
        <property name="userRepository" ref="userRepository"/>
    </bean>

    <bean id="userRepository" class="com.example.UserRepositoryImpl"/>
</beans>

  • 장점: 중앙 집중식 관리, 설정 변경 용이
  • 단점: 타입 안정성 부족, 대규모 프로젝트에서 복잡성 증가

3.2 Annotation 기반 설정

@Component
public class UserServiceImpl implements UserService {
    @Autowired
    private UserRepository userRepository;
}

@Repository
public class UserRepositoryImpl implements UserRepository {}

  • 주요 어노테이션:
    • @Component: 일반 Bean 등록
    • @Service, @Repository, @Controller: 계층별 특화 어노테이션
    • @Autowired: 의존성 자동 주입

3.3 Java Config 클래스 사용 (최신 추천 방식)

@Configuration
public class AppConfig {

    @Bean
    public UserService userService() {
        return new UserServiceImpl(userRepository());
    }

    @Bean
    public UserRepository userRepository() {
        return new UserRepositoryImpl();
    }
}

  • 장점:
    • 타입 안정성 보장
    • 컴파일 타임 오류 검출
    • 조건부 Bean 등록 가능(@Conditional)

4. Bean 설정 방법 비교표

구분 XML Annotation Java Config

설정 위치 외부 XML 파일 클래스 내부 전용 Config 클래스
장점 중앙 관리 용이 빠른 개발 가능 타입 안정성
단점 가독성 저하 과용 시 복잡성 설정 클래스 추가 필요
추천 사용처 레거시 시스템 소규모 프로젝트 중대형 프로젝트

5. Bean 생명주기 관리

@Bean(initMethod = "init", destroyMethod = "cleanup")
public ExampleBean exampleBean() {
    return new ExampleBean();
}

// 또는
@PostConstruct
public void init() {
    // 초기화 작업
}

@PreDestroy
public void cleanup() {
    // 종료 전 처리 작업
}

6. Bean Scope 설정

@Bean
@Scope("prototype") // 기본값은 singleton
public PaymentService paymentService() {
    return new PaymentService();
}

7. 설정 방식 혼합 사용 팁

  1. 주요 인프라 설정: Java Config
  2. 도메인 컴포넌트: Annotation
  3. 외부 라이브러리 연동: XML
  4. @Import 어노테이션으로 설정 클래스 모듈화

참고사항

  • Bean 이름을 커스텀 할 수도 있다
  • @Bean(name = "customAddr") public Address address(){ return new Address("Gogwan Street","Busan"); }
  • 클래스로도 접근가능
  • System.out.println(context.getBean("customAddr")); System.out.println(context.getBean(Address.class));
  • 레지스트에 등록된 Bean 출력 하는 법
  • // 함수형 프로그래밍 Arrays.stream(context.getBeanDefinitionNames()).forEach(System.out::println);

'Programming > Spring' 카테고리의 다른 글

Spring Container  (0) 2025.02.06
@Component와 @Bean의 차이  (0) 2025.02.06
Class 형태로 Bean 접근 방법  (0) 2025.02.06
Java Config 사용 Bean 설정  (0) 2025.02.06
SpringFramework의 개요  (0) 2025.02.06
Comments