스프링 프레임워크 5 입문 (6) - Java 코드를 통한 Bean 설정

김민영·2023년 6월 26일
0

Java 코드를 활용한 Bean 등록

JavaBeanConfiguration 프로젝트

  • 빈 등록
    • 지금까지 beans.xml 파일에서 빈 객체를 생성하고 java 코드에 가져와서 사용
    • java 코드에서 bean을 등록하기
    • xml 파일로 작성할 때는 값을 미리 지정해야 하는 반면, java 파일로 작성하는 것은 비교적 자유로움
  • Spring Context 생성
    • 기존
      • ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("kr/co/softcampus/config/beans.xml");
    • 변경
      • AnnotationCOnfigApplicationContext ctx = new AnnotationCOnfigApplicationContext();
      • ctx.register(BeanConfig.class);
      • ctx.refresh();

Annotation

@Configuration

  • 현재 자바 파일이 빈 등록을 위한 자바 파일임을 명시

@Bean

  • bean 객체 정의 시 사용
  • 메서드 이름 => bean 이름
  • @Bean(name=이름) : bean 이름 새로 정의
  • @Laze : lazy-init
  • @Scopte : bean scopte 설정
  • @Privary : primary 속성 지정

initdestroy 메서드

InitDestroy 프로젝트

init, destroy 메서드

  • 객체가 생성되거나 소멸될 때 자동으로 호출되는 메서드
  • init-method
  • destroy-method
  • Annotation
    • @Bean(initMethod = "init", destroyMethod = "destroy")

주입

JavaDI 프로젝트

  • 생성자 직접 호출 또는 setter 메서드를 직접 호출하는 방법
  • @Bean(autowire = 주입방식) : 자동 주입 방식 설정
  • Autowire.BY_NAME : 이름을 통한 자동 주입
  • Autowire.BY_TYPE : 타입을 통한 자동 주입
  • 스프링 5.1 부터 Deprecated. Bean에 직접 설정하는 방식 권장.

어노테이션을 이용한 빈 설정

AnnotationBean 프로젝트

  • xml이 아닌 어노테이션을 활용한 빈 설정
    • xml로 설정하려면 <context:annotation-config/> 태그 사용
  • bean.xml 변경
<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">
	
</beans>


	<!-- bean 클래스에 설정된 어노테이션 이용 -->
	<context:annotation-config></context:annotation-config>

@Required

  • 반드시 주입해야할 프로퍼티로 설정
  • 5.1 버전부터 deprecated. 반드시 주입해야할 프로퍼티는 생성자 주입 이용

@Autowired

  • 객체 타입을 통해 bean 객체를 자동 주입
  • 변수, 메서드 모두 주입 가능.

@Qualifier

  • Autowired로 주입 시, 같은 타입의 Bean 이 여러 개 있으면, Qualifier에 설정된 bean을 찾아 주입
  • @Qulifire("obj1")
  • 해당 bean이 없어도 오류가 나지 않으려면
    • Autowired(required = false)

생성자 주입

profile
노션에 1차 정리합니당 - https://cream-efraasia-f3c.notion.site/4fb02c0dc82e48358e67c61b7ce8ab36?v=

0개의 댓글