[Spring] DI(의존성 주입) @Configuration @Bean 어노테이션 사용방법

2022. 10. 26. 00:17·Back-End/Spring

https://hyunki99.tistory.com/64

 

[Spring] 스프링 프레임워크란?, 의존성 주입 방법 2가지 (IOC, DI, ApplicationContext 빈 가져오기)

스프링 프레임워크란 자바 플랫폼을 위한 오픈소스 애플리케이션 프레임워크로서 엔터프라이즈급을 개발하기 위한 모든 기능을 종합적으로 제공하는 경량화된 솔루션입니다. ✔ 엔터프라이즈

hyunki99.tistory.com

지난 글에서 DI 2가지 방법(Setter, 생성자)을 알아봤습니다.

 

더 편리하게 의존성 주입을 할 수 있는

어노테이션 방법이 더 있다고 합니다.

@Configuration @Bean 어노테이션에 대해 알아봅시다. 😀

 

프로그램이 거대해 짐에 따라 XML을 이용하여 IOC Container를 설정하는 것이 어려워 졌고
때문에 Annotation(@)이 등장했습니다. 어노테이션은 코드에 메타데이터를 작성하여
직관적인 코딩이 가능하게 만들어주며 이에 따라 생산성이 증대되는 장점을 가지고 있습니다.
출처 : https://galid1.tistory.com/494

 

 


📝 @Configuration & @Bean

 

@Configuration 어노테이션은 스프링 IOC Container에게

해당 클래스를 Bean 구성 Class임을 알려줍니다.

클래스 내에서 빈즈를 메서드처럼 선언하여 사용합니다.

 

✔ 장점
1. 스프링 컨테이너에서 Bean을 관리할 수 있게 됩니다.

2. Bean을 등록할 때 싱글톤(singleton)이 되도록 보장해 줍니다.
@Configuration을 사용하면 CGLIB라는 결과가 붙습니다.
스프링에서 CGLIB라는 바이트코드 조작 라이브러리를 사용해서 AppConfig를 상속받은
임의의 클래스를 만들고 그것을 스프링 빈으로 등록했기 때문에 싱글톤이 되는 것을 유지해 준다고 합니다.

 

⦁ 사용 방법

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

@Configuration
public class ApplicationConfig {
	
	@Bean
	public Student student1() {
		ArrayList<String> hobbys = new ArrayList<String>();
		hobbys.add("수영");
		hobbys.add("요리");
		
		Student student = new Student("홍길동", 20, hobbys);
		student.setHeight(180);
		student.setWeight(80);
		
		return student;
	}
}

 

⦁ 전체 소스코드 

더보기

⦁ MainClass.java

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class MainClass {
	public static void main(String[] args) {
        	//컨테이너 생성
		AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(ApplicationConfig.class);
		
        	//빈 가져오기
		Student student1 = ctx.getBean("student1", Student.class);
		System.out.println("이름 :"+student1.getName());
		System.out.println("나이 :"+student1.getAge());
		System.out.println("취미 :"+student1.getHobbys());
		System.out.println("신장 :"+student1.getHeight());
		System.out.println("몸무게 :"+student1.getWeight());

		ctx.close();
	}
}

✔ 실행하는 메인 클래스입니다.

 

⦁ Student 빈즈

import java.util.ArrayList;
import java.util.List;

public class Student {
	private String name;
	private int age;
	private ArrayList<String> hobbys;
	private int height;
	private int weight;
	
	public int getHeight() {
		return height;
	}

	public void setHeight(int height) {
		this.height = height;
	}

	public int getWeight() {
		return weight;
	}

	public void setWeight(int weight) {
		this.weight = weight;
	}

	public Student() {
	}
	
	public ArrayList<String> getHobbys() {
		return hobbys;
	}

	public void setHobbys(ArrayList<String> hobbys) {
		this.hobbys = hobbys;
	}

	public Student(String name, int age, ArrayList<String> hobbys) {
		this.name = name;
		this.age = age;
		this.hobbys = hobbys; 
	}
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
}

✔ 필드와 Get / Set을 가지고 있는 자바 빈즈입니다.

 

 


 


📝 @ImportResource

 

✔ @ImportResource 어노테이션을 사용하면

자바파일에 xml에 존재하는 빈을 가져올 수도 있습니다.

   

⦁ applicationCTX.xml 설정

✔ 하단 Namespaces 선택 -> Context 체크

 

<beans> 태그의 네임 스페이스에 다음 속성이 추가됩니다.

xmlns:context="http://www.springframework.org/schema/context"

 

⦁ applicationCTX.xml 전체 코드

더보기
<?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 http://www.springframework.org/schema/context/spring-context-3.1.xsd">
	
	<!-- xml에서 어노테이션 사용 -->
	<bean id="student1" class="com.company.day2.Student">
		<constructor-arg>
			<value>홍길동</value>
		</constructor-arg>
		
		<constructor-arg>
			<value>24</value>	
		</constructor-arg>

		<constructor-arg>
			<list>
				<value>수영</value>
				<value>요리</value>
			</list>
		</constructor-arg>
		<property name="height" value="190"/>
		<property name="weight" value="70"/>
	</bean>
</beans>

 

⦁ ApplicationConfig.java

//applicationConfig.java

@Configuration
@ImportResource("classpath:applicationCTX.xml")

@ImportResource 어노테이션을 추가해주면

xml파일에 있는 빈을 가져올 수 있게 됩니다.

 

// ApplicationConfig.java 파일

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

@Configuration
@ImportResource("classpath:applicationCTX.xml")
public class ApplicationConfig {
	
//	@Bean
//	public Student student1() {
//		ArrayList<String> hobbys = new ArrayList<String>();
//		hobbys.add("수영");
//		hobbys.add("요리");
//		
//		Student student = new Student("홍길동", 20, hobbys);
//		student.setHeight(180);
//		student.setWeight(80);
//		
//		return student;
//	}
}

 

✔ 전부 주석처리 해주고 메인 클래스를 실행하면

xml에 존재하는 빈을 성공적으로 불러온 모습을 확인할 수 있습니다.

 


 


 

 

스프링 3.0에서는 어노테이션을 많이 사용하고

버전이 올라가면서 섞어서도 많이 사용한다고 합니다.

 

팀의 상황에 맞게 사용하겠지만, 원활한 협업을 위해서는

내가 아닌 남이 사용하는 방법도 숙지해야 합니다.😀

 

 


참고 문헌 : 

 

https://castleone.tistory.com/2

https://galid1.tistory.com/494

 

'Back-End > Spring' 카테고리의 다른 글

[Spring] 자바 스프링 AOP란?, AOP 개념 정리 (프록시, AspectJ)  (0) 2022.10.27
[Spring] 자바 스프링 한글 깨짐 해결 (filter)  (0) 2022.10.27
[Spring] 자바 스프링 프로퍼티(properties) 파일 데이터 가져오기  (0) 2022.10.27
[Spring] 스프링 프레임워크란?, 의존성 주입 방법 2가지 (IOC, DI, ApplicationContext 빈 가져오기)  (0) 2022.10.24
[Spring] 이클립스 자바 스프링 설치 방법  (0) 2022.10.24
'Back-End/Spring' 카테고리의 다른 글
  • [Spring] 자바 스프링 한글 깨짐 해결 (filter)
  • [Spring] 자바 스프링 프로퍼티(properties) 파일 데이터 가져오기
  • [Spring] 스프링 프레임워크란?, 의존성 주입 방법 2가지 (IOC, DI, ApplicationContext 빈 가져오기)
  • [Spring] 이클립스 자바 스프링 설치 방법
현기
현기
  • 현기
    현기의 개발블로그
    현기
  • 전체
    오늘
    어제
    • 분류 전체보기 (120)
      • Front-End (39)
        • Next (5)
        • React (8)
        • React Native (11)
        • Flutter (0)
        • Vue (1)
        • JSP (9)
        • HTML, CSS, JS (5)
      • Back-End (16)
        • Node.js (3)
        • Spring (8)
        • Flask (1)
        • AWS (4)
      • DB (5)
        • Oracle (4)
        • MySQL (1)
      • Python (7)
      • Java (27)
        • 자바 이론 (17)
        • 코딩테스트 연습 & 실습 (10)
      • 자료구조 & 알고리즘 (7)
        • 코딩테스트 (6)
        • 알고리즘 (1)
      • 블록체인 (0)
      • 프롬프트 엔지니어링 (0)
      • CS 지식 (5)
      • IT뉴스 (0)
      • 일상 (3)
      • etc (11)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    Python
    포스트맨
    Java
    DI
    티스토리챌린지
    Express
    오블완
    react-native-chart-kit
    자바 스프링
    IS-A
    자바
    자바스크립트
    react
    스택
    서블릿
    JDBC
    JSP
    next-intl
    상속
    React Native
    쓰레드
    Spring
    React Native Chart
    오라클
    그리디
    파이썬
    큐
    리액트 네이티브
    REST API
    node.js
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.1
현기
[Spring] DI(의존성 주입) @Configuration @Bean 어노테이션 사용방법
상단으로

티스토리툴바