728x90
반응형

[Spring Boot] Spring Boot 개요 - 초보자를 위한 핵심 개념 정리

 

[Spring Boot] Spring Boot 개요 - 초보자를 위한 핵심 개념 정리

1. 스프링 부트(Spring Boot) 개요1. 스프링 부트란?필요한 환경 설정을 최소화하고 개발자가 비즈니스 로직에 집중할 수 있도록 도와줘 생산성을 크게 향상시킬 수 있도록 스프링의 단점을 보완하

crushed-taro.tistory.com

1. @RequestMapping

@RequestMapping은 Spring Web MVC에서 요청(Request)을 처리하는 데 사용되는 어노테이션이며, 클래스 레벨이나 메소드 레벨에서 사용 가능하다. 이를 통해 어떤 URL이 어떤 메소드에서 처리되는지, 어떤 HTTP Method를 처리할지 등을 정할 수 있다.
  • DispatcherServlet은 웹 요청을 받으면 @Controller가 달린 컨트롤러 클래스에 처리를 위임한다. 그 과정은 컨트롤러 클래스의 핸들러 메서드에 선언된 다양한 @RequestMapping 설정 내용에 따른다.

 

1. Method Mapping

클래스를 생성하고 @Controller 어노테이션을 설정 한 뒤 요청 매핑 테스트를 진행한다.

@Controller 어노테이션이 붙은 클래스는 웹 요청을 처리하는 컨트롤러임을 나타내며, Spring MVC에서는 @Controller 어노테이션이 붙은 클래스를 자동으로 스캔해서 Bean으로 등록한다. 이후 요청이 들어오면 @RequestMapping 어노테이션을 이용하여 어떤 메소드가 요청을 처리할지 지정한다.

 

1. Method 방식 미지정

@Controller 어노테이션이 설정 된 클래스에 @RequestMapping 어노테이션을 설정한 메소드를 정의한다. 그리고  @RequestMapping에는 요청 URL 값을 설정한다.

 

/* 요청 URL 설정 */
@RequestMapping("/menu/regist")
public String registMenu(Model model) {
	
	/* Model 객체에 addAttribute 메서드를 이용해 
	 * key, value를 추가하면 추후 view에서 사용할 수 있다.
   * chap03-view-resolver에서 다시 다룬다. */	
	model.addAttribute("message", "신규 메뉴 등록용 핸들러 메소드 호출함...");
	
	/* 반환 하고자 하는 view의 경로를 포함한 이름을 작성한다. 
   * resources/templates 하위부터의 경로를 작성한다.
   * chap03-view-resolver에서 다시 다룬다. */	
	return "mappingResult";
}

 

요청에 대해 반환하고자 하는 view를 생성하고 model 객체에 추가했던 message를 화면에 출력하는 thymeleaf 코드를 작성한다. thymeleaf는 뷰 템플릿의 한 종류인데 자세한 문법은 추후 다룬다. 여기에서는 th:text="${key}"를 통해 값을 화면에 출력하도록 한다.

 

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>result</title>
</head>
<body>
    <h3 th:text="${ message }"></h3>
</body>
</html>

 

index.html 페이지에서GET 방식과 POST 방식의 요청을 둘 다 전달하여 테스트 해본다.

 

<h3>GET : /menu/regist</h3>
<button onclick="location.href='/menu/regist'">GET 메뉴 등록 요청</button>

<h3>POST : /menu/regist</h3>
<form action="/menu/regist" method="post">
	<button type="submit">POST 메뉴 등록 요청</button>
</form>

 

GET 방식과 POST 방식 모두 응답을 확인할 수 있다. 즉 RequestMapping 설정에 method 방식을 지정하지 않으면 get/post 요청을 다 처리한다.

 

2. Method 방식 지정

이번에는 @RequestMapping 어노테이션에 value 속성과 method 속성을 지정해 본다.  method 속성에는 RequestMethod.GET이라고 method 방식을 제한해서 기재한다.

 

/* 요청 URL을 value 속성에 요청 method를 method 속성에 설정 */
@RequestMapping(value = "/menu/modify", method = RequestMethod.GET)
public String modifyMenu(Model model) {
		
	model.addAttribute("message", "GET 방식의 메뉴 수정용 핸드러 메소드 호출함...");
		
	return "mappingResult";
}

 

index.html 페이지에GET 방식과 POST 방식의 요청을 둘 다 전달하여 테스트 해본다.

 

<h3>GET : /menu/modify</h3>
<button onclick="location.href='/menu/modify'">GET 메뉴 수정 요청</button>

<h3>POST : /menu/modify</h3>
<form action="/menu/modify" method="post">
  <button type="submit">POST 메뉴 수정 요청</button>
</form>

 

GET 방식은 응답이 오지만 POST 방식은 에러가 발생하여 스프링 부트 프로젝트의 기본 에러 페이지가 응답된다. 405 에러는 허용 되지 않는 메소드를 요청했을 때 발생하며 POST방식은 제공 되지 않으므로 에러가 발생하는 것이다.
 

3. 요청 메소드 전용 어노테이션(since 4.3)

요청 메소드 어노테이션
GET @GetMapping
POST @PostMapping
PUT @PutMapping
DELETE @DeleteMapping
PATCH @PatchMapping

 

이 어노테이션들은 @RequestMapping 어노테이션에 method 속성을 사용하여 요청 방법을 지정하는 것과 같다. 각 어노테이션은 해당하는 요청 메소드에 대해서만 처리할 수 있도록 제한하는 역할을 한다.

 

@GetMapping("/menu/delete")
public String getDeleteMenu(Model model) {
		
	model.addAttribute("message", "GET 방식의 삭제용 핸들러 메소드 호출함...");
		
	return "mappingResult";
}
	
@PostMapping("/menu/delete")
public String postDeleteMenu(Model model) {
		
	model.addAttribute("message", "POST 방식의 삭제용 핸들러 메소드 호출함...");
		
	return "mappingResult";
}

 

index.html 페이지에서 GET 방식과 POST 방식의 요청을 둘 다 전달하여 테스트 해본다.

GET 방식과 POST 방식 모두 각각의 핸들러 메소드와 잘 매핑 되어 응답이 돌아오는 것을 확인할 수 있다.

728x90
반응형
728x90
반응형

1. 스프링 부트(Spring Boot) 개요

1. 스프링 부트란?

  • 필요한 환경 설정을 최소화하고 개발자가 비즈니스 로직에 집중할 수 있도록 도와줘 생산성을 크게 향상시킬 수 있도록 스프링의 단점을 보완하여 만든 프로젝트이다.
  • 스프링 부트는 틀림없이 자바에서 REST 기반 마이크로서비스 웹 애플리케이션을 개발하는 가장 빠른 방법 중 하나로 도커 컨테이너 배포 및 빠른 프로토타이핑에도 매우 적합하다.
  • 간혹 스프링부트를 스프링 프레임워크와 전혀 다른 것으로 오해하지만 스프링부트는 스프링프레임워크라는 큰 틀 속에 속하는 도구일 뿐이다.

 

Spring Boot를 사용하면 "그냥 실행할 수 있는" 독립 실행형 production-grade Spring 기반 애플리케이션을 쉽게 생성할 수 있다.우리는 당신이 최소한의 고민으로 시작할 수 있도록 Spring 플랫폼과 third-party libraries에 대한 견해를 가지고 있다. 대부분의 Spring Boot 애플리케이션은 최소한의 Spring 구성으로 동작시킬 수 있다.
출처 : https://spring.io/projects/spring-boot
 

Spring Boot

 

spring.io

 

2. 스프링 부트 역사

  • 2012년 10월 Mike Youngstrom는 Spring 프레임워크에서 컨테이너 없는 웹 애플리케이션 아키텍처에 대한 지원을 요청하는 기능 요청했다. main 메소드에서 부트스트랩된 스프링 컨테이너 내에서 웹 컨테이너 서비스를 구성하는 것에 대해 말했는데 다음은 '이슈' 기반의 프로젝트 관리 도구 jira 요청에서 발췌한 내용이다.
Spring 컴포넌트와 설정 모델을 위에서 아래로 활용하는 도구와 참조 아키텍처를 제공한다면 Spring의 웹 애플리케이션 아키텍처는 상당히 단순화될 수 있다고 생각한다. 간단한 main() 메소드에서 부트스트랩된 Spring Container 내에 이러한 공통 웹 컨테이너 서비스의 구성을 포함하고 통합한다.
  • Mike Youngstrom의 요청으로 인해 2013년 초에 시작되는 스프링 부트 프로젝트 개발이 시작되었고 2014년 4월에 스프링 부트 1.0.0이 릴리즈 되었다. 그 이후로 많은 스프링 부트 마이너 버전이 나왔다.
  • https://github.com/spring-projects/spring-boot/wiki
 

Home

Spring Boot helps you to create Spring-powered, production-grade applications and services with absolute minimum fuss. - spring-projects/spring-boot

github.com

 

3. 스프링 부트의 특징

  • 임베디드 톰캣(Embed Tomcat), 제티, 언더토우를 사용하여 독립 실행이 가능한 스프링 애플리케이션 개발
  • 통합 스타터를 제공하여 메이븐/그레이들 구성 간소화
  • 스타터를 통한 자동화된 스프링 설정 제공
  • 번거로운 XML 설정을 요구하지 않음
  • JAR 를 사용하여 자바 옵션만으로 배포 가능
  • 애플리케이션의 모니터링과 관리를 위한 스프링 액츄에이터(Spring Actuator) 제공

 

4. 스프링 부트의 사용 이유

1. 스프링 부트의 장점

  • 각각의 의존성 버젼을 쉽게 올리는 것이 가능하다. (수동으로 설정하던 기존의 방식에 비해 안정된 버전 제공을 보장받을 수 있음)
  • 간단한 어노테이션/프로퍼티 설정으로 원하는 기능을 빠르게 적용할 수 있다.
  • 별도의 외장 톰캣을 설치할 필요가 없고 톰캣 버젼도 편리하게 관리할 수 있다.
  • 특정 라이브러리에 버그가 있더라도 이후에 스프링팀에서 버그를 수정하면 수정된 버전을 받기에 편리하다.

 

2. 스프링 부트의 단점

  • 설정을 커스터마이징 해야 하는 경우 기존 스프링프레임워크를 사용하는 것과 같은 어려움을 겪을 수 있다.
  • 설정을 변경하고 싶은 경우 정확한 동작 원리와 내부 코드를 살펴봐야 하는 불편함이 있다.

 

5. 스프링 부트의 핵심 요소

1. 스프링 부트의 핵심 요소의 종류

요소 기능
스타터(Starter) 스프링의 특정 모듈을 사용할 수 있도록 관련된 라이브러리 의존성을 해결
자동설정(Autoconfiguration) Starter로 추가한 모듈을 사용할 수 있도록 빈 설정을 자동으로 관리
액추에이터(Actuator) 스프링부트로 개발된 시스템을 모니터링할 수 있는 기능들을 제공

 

6. 스타터(Starter)

1. 스타터란?

  • 의존성과 설정을 자동화 해주는 모듈을 뜻하며 필요한 라이브러리들을 관련있는 것들을 묶어서 제공한다.
  • 라이브러리간의 의존관계를 파악하고 dependency들의 상속관계를 통해 작성되어 필요한 라이브러리를 다운로드 받아준다.

 

2. 스프링 부트 스타터 명명 규칙

  • spring-boot-starter-*
  • 스프링부트의 기본 스타터 종류
스타터명 설명
spring-boot-starter 스프링 부트의 코어 (auto-configuration, logging, yaml 등을 제공)
spring-boot-starter-aop AOP(Aspect Oriented Programming)를 위한 스타터
spring-boot-starter-batch Spring Batch를 사용하기 위한 스타터
spring-boot-starter-jpa Spring Data JPA와 Hibernate를 위한 스타터
spring-boot-starter-data-redis Redis와 Jedis 사용에 필요한 스타터
spring-boot-starter-data-rest Spring Data REST를 사용하기 위한 스타터
spring-boot-starter-thymleaf Thymeleaf 템플릿 엔진 사용에 필요한 스타터
spring-boot-starter-jdbc JDBC Connection Pool 사용에 필요한 스타터
spring-boot-starter-security Sprint Security 사용에 필요한 스타터
spring-boot-starter-oauth2 OAuth2 인증 사용에 필요한 스타터
spring-boot-starter-validation Java Bean Validation 사용에 필요한 스타터
spring-boot-starter-web 웹 개발을 위해 필요한 스타터(Spring MVC, REST, Embed Tomcat, 기타 라이브러리 등)

 

3. 스프링부트 스타터 의존성 확인

 

Build Systems :: Spring Boot

Each release of Spring Boot provides a curated list of dependencies that it supports. In practice, you do not need to provide a version for any of these dependencies in your build configuration, as Spring Boot manages that for you. When you upgrade Spring

docs.spring.io

728x90
반응형
728x90
반응형

1. Proxy

Java에서 프록시(Proxy)는 대리자를 의미한다. 프록시는 기존의 객체를 감싸서 그 객체의 기능을 확장하거나 변경할 수 있게 해준다. 예를 들어, 프록시 객체를 사용하면 객체에 대한 접근을 제어하거나, 객체의 메소드 호출 전후에 로깅 작업 등을 수행할 수 있다. 또한, 프록시 객체를 사용하여 원격으로 실행되는 객체를 호출할 수도 있다. 프록시는 주로 AOP(Aspect Oriented Programming)에서 사용된다.
  • 프록시 생성은 크게 두 가지 방식이 제공된다.
  1. 1. JDK Dynamic Proxy 방식
    • 리플렉션을 이용해서 proxy 클래스를 동적으로 생성해주는 방식으로, 타겟의 인터페이스를 기준으로 proxy를 생성해준다. 사용자의 요청이 타겟을 바라보고 실행될 수 있도록 타겟 자체에 대한 코드 수정이 아닌 리플렉션을 이용한 방식으로, 타겟의 위임 코드를InvocationHandler를 이용하여 작성하게 된다. 하지만 사용자가 타겟에 대한 정보를 잘못 주입하는 경우가 발생할 수 있기 때문에 내부적으로 주입된 타겟에 대한 검증 코드를 거친 후 invoke가 동작하게 된다.
  2. CGLib 방식
    • 동적으로 Proxy를 생성하지만 바이트코드를 조작하여 프록시를 생성해주는 방식이다. 인터페이스 뿐 아니라 타겟의 클래스가 인터페이스를 구현하지 않아도 프록시를 생성해준다. CGLib(Code Generator Library)의 경우에는 처음 메소드가 호출된 당시 동적으로 타켓 클래스의 바이트 코드를 조작하게 되고, 그 이후 호출 시부터는 변경된 코드를 재사용한다. 따라서 매번 검증 코드를 거치는 1번 방식보다는 invoke시 더 빠르게 된다. 또한 리플렉션에 의한 것이 아닌 바이트코드를 조작하는 방식이기 때문에 성능면에서는 더 우수하다.

하지만 CGLib 방식은 스프링에서 기본적으로 제공되는 방식은 아니었기에 별도로 의존성을 추가하여 개발해야 했고, 파라미터가 없는 default 생성자가 반드시 필요했으며, 생성된 프록시의 메소드를 호출하면 타겟의 생성자가 2번 호출되는 등의 문제점들이 있었다.

스프링 4.3, 스프링부트 1.3 이후부터 CGLib의 문제가 된 부분이 개선되어 기본 core 패키지에 포함되게 되었고, 스프링에서 기본적으로 사용하는 프록시 방식이 CGLib 방식이 되었다.

 

1. 로직을 포함하는 코드 작성

  • Student 인터페이스 작성
public interface Student {
	
	void study(int hours);
}

 

  • Student 클래스 작성 (Student인터페이스 구현)
public class Student implements Student {
	
	 @Override
     public void study(int hours) {
        System.out.println(hours + "시간 동안 열심히 공부합니다.");
     }
}

 

2. dynamic

1. Handler 클래스 작성

java.lang.reflect.InvocationHandler를 구현한 클래스를 작성한다.

Student 클래스를 타겟 인스턴스로 설정하고 invoke 메소드를 정의한다.

public class Handler implements InvocationHandler {
	
	/* 메소드 호출을 위해 타겟 인스턴스가 필요하다 */
	private final Student student;
     
  public Handler(Student student) {
    this.student = student;
  }
    
  /* 생성된 proxy 인스턴스와 타겟 메소드, 전달받은 인자를 매개변수로 한다. */
  @Override
  public Object invoke(Object proxy, Method method, Object[] args) 
		throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
    	
    System.out.println("============ 공부가 너무 하고 싶습니다. ==============");
    System.out.println("호출 대상 메소드 : " + method);
    for(Object arg : args) {
    	System.out.println("전달된 인자 : " + arg);
    }
    	
   /* 타켓 메소드를 호출한다. 타겟 Object와 인자를 매개변수로 전달한다. 
    * 여기서 프록시를 전달하면 다시 타겟을 호출할 때 다시 프록시를 생성하고 다시 또 전달하는 무한 루프에 빠지게 된다.
    * */
   method.invoke(student, args);
    	 
   System.out.println("============ 공부를 마치고 수면 학습을 시작합니다. ============");
    	 
   return proxy;
    	 
  }
}

 

2. Application 실행 클래스 작성

Student student = new Student();
Handler handler = new Handler(student);
		
/* 클래스로더, 프록시를 만들 클래스 메타 정보(인터페이스만 가능), 프록시 동작할 때 적용될 핸들러 */
Student proxy 
= (Student) Proxy.newProxyInstance(Student.class.getClassLoader(), new Class[] {Student.class}, handler);
	    
/* 프록시로 감싸진 인스턴스의 메소드를 호출하게 되면 핸들러에 정의한 메소드가 호출된다. */
proxy.study(16);

/*
============ 공부가 너무 하고 싶습니다. ==============
호출 대상 메소드 : public abstract void Student.study(int)
전달된 인자 : 16
16시간 동안 열심히 공부합니다.
============ 공부를 마치고 수면 학습을 시작합니다. ============
*/

 

  • study 메소드 호출 시 proxy 객체의 동작을 확인할 수 있다.

 

3. cglib

1. Handler 클래스 작성

org.springframework.cglib.proxy.InvocationHandler를 구현한 클래스를 작성한다.

Student 클래스를 타겟 인스턴스로 설정하고 invoke 메소드를 정의한다.

public class Handler implements InvocationHandler {
	
	private final Student student;
     
  public Handler(Student student) {
   this.student = student;
  }
    
  @Override
  public Object invoke(Object proxy, Method method, Object[] args) 
		throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
    	
  	System.out.println("============ 공부가 너무 하고 싶습니다. ==============");
   	System.out.println("호출 대상 메소드 : " + method);
   	for(Object arg : args) {
   		System.out.println("전달된 인자 : " + arg);
   	}
    	
   	method.invoke(student, args);
    	 
   	System.out.println("============ 공부를 마치고 수면 학습을 시작합니다. ============");
    	 
   	return proxy;
   	 
  }
}

 

2. Application 실행 클래스 작성

Student student = new Student();
Handler handler = new Handler(student);
		
/* Enhancer 클래스의 create static 메소드는 타겟 클래스의 메타정보와 핸들러를 전달하면 proxy를 생성해서 반환해준다. */
Student proxy 
= (Student) Enhancer.create(Student.class, new Handler(new Student()));

proxy.study(20);

/*
============ 공부가 너무 하고 싶습니다. ==============
호출 대상 메소드 : public void Student.study(int)
전달된 인자 : 20
20시간 동안 열심히 공부합니다.
============ 공부를 마치고 수면 학습을 시작합니다. ============
*/
  • study 메소드 호출 시 proxy 객체의 동작을 확인할 수 있다.
728x90
반응형
728x90
반응형

[Spring Framework] Spring AOP 구현하기 | 예제 포함

 

[Spring Framework] Spring AOP 구현하기 | 예제 포함

[Spring Framework] [Spring AOP] 종류와 특징 총정리 – 입문자를 위한 기초 가이드 [Spring Framework] [Spring AOP] 종류와 특징 총정리 – 입문자를 위한 기초 가이드[Spring Framework] 초보자를 위한 Spring Bean Proper

crushed-taro.tistory.com

1. Reflection

Java 리플렉션(Reflection)은 실행 중인 자바 프로그램 내부의 클래스, 메소드, 필드 등의 정보를 분석하여 다루는 기법을 말한다. 이를 통해 프로그램의 동적인 특성을 구현할 수 있다. 예를 들어, 리플렉션을 이용하면 실행 중인 객체의 클래스 정보를 얻어오거나, 클래스 내부의 필드나 메소드에 접근할 수 있다. 이러한 기능들은 프레임워크, 라이브러리, 테스트 코드 등에서 유용하게 활용된다.

⇒ 스프링에서는 이 Reflection 기술을 사용해 런타임 시 등록한 빈을 애플리케이션 내에서 사용할 수 있게 한다.

 

1. 로직을 포함하는 코드 작성

플렉션 테스트의 대상이 될Account클래스를 생성한다.

public class Account {
	
	private String bankCode;
	private String accNo;
	private String accPwd;
	private int balance;
	
	public Account() {}
	
	public Account(String bankCode, String accNo, String accPwd) {
		this.backCode = bankCode;
		this.accNo = accNo;
		this.accPwd = accPwd;
	}
	
	public Account(String bankCode, String accNo, String accPwd, int balance) {
		this(bankCode, accNo, accPwd);
		this.balance = balance;
	}
	
	/* 현재 잔액을 출력해주는 메소드 */
	public String getBalance() {
		
		return this.accNo + " 계좌의 현재 잔액은 " + this.balance + "원 입니다.";
	}
	
	/* 금액을 매개변수로 전달 받아 잔액을 증가(입금) 시켜주는 메소드 */
	public String deposit(int money) {
		
		String str = "";
		
		if(money >= 0) {
			this.balance += money;
			str = money + "원이 입급되었습니다.";
		}else {
			str = "금액을 잘못 입력하셨습니다.";
		}
		
		return str;
	}
	
	/* 금액을 매개변수로 받아 잔액을 감소(출금) 시켜주는 메소드 */
	public String withDraw(int money) {
		
		String str = "";
		
		if(this.balance >= money) {
			this.balance -= money;
			str = money + "원이 출금되었습니다.";
		}else {
			str = "잔액이 부족합니다. 잔액을 확인해주세요.";
		}

		return str;
	}
}

 

2. 리플렉션 테스트

1. Class

Class타입의 인스턴스는 해당 클래스의 메타정보를 가지고 있는 클래스이다.

/* .class 문법을 이용하여 Class 타입의 인스턴스를 생성할 수 있다. */
Class class1 = Account.class;
System.out.println("class1 : " + class1);
		
/* Object 클래스의 getClass() 메소드를 이용하면 Class 타입으로 리턴받아 이용할 수 있다. */
Class class2 = new Account().getClass();
System.out.println("class2 : " + class2);

/* Class.forName() 메소드를 이용하여 런타임시 로딩을 하고 그 클래스 메타정보를 Class 타입으로 반환받을 수 있다. */
try {
	Class class3 = Class.forName("project.reflection.Account");
	System.out.println("class3 : " + class3);
			
	/* Double자료형 배열을 로드할 수 있다. */
	Class class4 = Class.forName("[D");
	Class class5 = double[].class;
			
	System.out.println("class4 : " + class4);
	System.out.println("class5 : " + class5);
			
	/* String자료형 배열을 로드할 수 있다. */
	Class class6 = Class.forName("[Ljava.lang.String;");
	Class class7 = String[].class;
	System.out.println("class6 : " + class6);
	System.out.println("class7 : " + class7);
			
} catch (ClassNotFoundException e) {
	e.printStackTrace();
}
		
/* 원시 자료형을 사용하면 컴파일 에러 발생 */
//		double d = 1.0;
//		Class class8 = d.getClass();
		
/* TYPE 필드를 이용하여 원시형 클래스를 반환받을 수 있다. */
Class class8 = Double.TYPE;
System.out.println("class8 : " + class8);
		
Class class9 = Void.TYPE;
System.out.println("class9 : " + class9);
		
/* 클래스의 메타 정보를 이용하여 여러 가지 정보를 반환받는 메소드를 제공한다. */
/* 상속된 부모 클래스를 반환한다. */
Class superClass = class1.getSuperclass();
System.out.println("superClass : " + superClass);

/*
class1 : class project.reflection.Account
class2 : class project.reflection.Account
class3 : class project.reflection.Account
class4 : class [D
class5 : class [D
class6 : class [Ljava.lang.String;
class7 : class [Ljava.lang.String;
class8 : double
class9 : void
superClass : class java.lang.Object
*/

 

2. field

field 정보에 접근할 수 있다.

Field[] fields = Account.class.getDeclaredFields();
for(Field field : fields) {
	System.out.println("modifiers : " + Modifier.toString(field.getModifiers()) + 
			", type : " + field.getType() + 
			", name : " + field.getName() );
}

/*
modifiers : private, type : class java.lang.String, name : backCode
modifiers : private, type : class java.lang.String, name : accNo
modifiers : private, type : class java.lang.String, name : accPwd
modifiers : private, type : int, name : balance
*/

 

3. 생성자

생성자 정보에 접근할 수 있다.

Constructor[] constructors = Account.class.getConstructors();
for(Constructor con : constructors) {
	System.out.println("name : " + con.getName());
			
	Class[] params = con.getParameterTypes();
	for(Class param : params) {
		System.out.println("paramType : " + param.getTypeName());
	}
}

/*
name : project.reflection.Account
paramType : java.lang.String
paramType : java.lang.String
paramType : java.lang.String
paramType : int
name : project.reflection.Account
paramType : java.lang.String
paramType : java.lang.String
paramType : java.lang.String
name : project.reflection.Account
*/

 

생성자를 이용하여 인스턴스를 생성할 수 있다.

try {
	Account acc = (Account) constructors[0].newInstance("20", "110-223-123456", "1234", 10000);
	System.out.println(acc.getBalance());
} catch (InstantiationException | IllegalAccessException | IllegalArgumentException
		| InvocationTargetException e) {
		e.printStackTrace();
}

/*
110-223-123456 계좌의 현재 잔액은 10000원 입니다.
*/

 

4. 생성자

메소드 정보에 접근할 수 있다.

Method[] methods = Account.class.getMethods();
Method getBalanceMethod = null;
for(Method method : methods) {
	System.out.println(Modifier.toString(method.getModifiers()) + " " + 
					method.getReturnType().getSimpleName() + " " + 
					method.getName());
			
	if("getBalance".equals(method.getName())) {
		getBalanceMethod = method;
	}
}

/*
public String getBalance
public String withDraw
public String deposit
public final native void wait
public final void wait
public final void wait
public boolean equals
public String toString
public native int hashCode
public final native Class getClass
public final native void notify
public final native void notifyAll
*/

 

invoke 메소드로 메소드를 호출할 수 있다.

try {
	System.out.println(getBalanceMethod.invoke(((Account) constructors[2].newInstance())));
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
	e.printStackTrace();
} catch (InstantiationException e) {
	e.printStackTrace();
}

/*
null 계좌의 현재 잔액은 0원 입니다.
*/
728x90
반응형
728x90
반응형

[Spring Framework] [Spring AOP] 종류와 특징 총정리 – 입문자를 위한 기초 가이드

 

[Spring Framework] [Spring AOP] 종류와 특징 총정리 – 입문자를 위한 기초 가이드

[Spring Framework] 초보자를 위한 Spring Bean Properties 가이드 [Spring Framework] 초보자를 위한 Spring Bean Properties 가이드[Spring Framework] Spring Boot Bean 초기화(init)와 소멸(destroy) 메서드 완전 정리 [Spring Framework]

crushed-taro.tistory.com

1. Spring AOP

1. 로직을 포함하는 코드 작성

1. MemberDTO 클래스 생성

@AllArgsConstructor
@ToString
public class MemberDTO {

    private Long id;
    private String name;
}

 

2. MemberDAO

@Repository
public class MemberDAO {

    private final Map<Long, MemberDTO> memberMap;

    public MemberDAO(){
        memberMap = new HashMap<>();
        memberMap.put(1L, new MemberDTO(1L, "유관순"));
        memberMap.put(2L, new MemberDTO(2L, "홍길동"));
    }

    public Map<Long, MemberDTO> selectMembers(){

        return memberMap;
    };

    public MemberDTO selectMember(Long id) {

        MemberDTO returnMember = memberMap.get(id);

        if(returnMember == null) throw new RuntimeException("해당하는 id의 회원이 없습니다.");

        return returnMember;
    }
}

 

3. MemberService 클래스 생성

@Service
public class MemberService {

    private final MemberDAO memberDAO;

    public MemberService(MemberDAO memberDAO) {
        this.memberDAO = memberDAO;
    }

		public Map<Long, MemberDTO> selectMembers(){
        System.out.println("selectMembers 메소드 실행");
        return memberDAO.selectMembers();
    }

    public MemberDTO selectMember(Long id) {
        System.out.println("selectMember 메소드 실행");
        return memberDAO.selectMember(id);
    }
}

 

4. Application 클래스 생성

public class Application {
    public static void main(String[] args) {

        ApplicationContext context 
					= new AnnotationConfigApplicationContext("project.aop");

        MemberService memberService = context.getBean("memberService", MemberService.class);
        System.out.println("=============== selectMembers ===============");
        System.out.println(memberService.selectMembers());
        System.out.println("=============== selectMember ===============");
        System.out.println(memberService.selectMember(3L));

    }
}

/*
=============== selectMembers ===============
{1=MemberDTO(id=1, name=유관순), 2=MemberDTO(id=2, name=홍길동)}
=============== selectMember ===============
Exception in thread "main" java.lang.RuntimeException: 해당하는 id의 회원이 없습니다.
...생략
*/

 

2. 라이브러리 의존성 추가

aspectjweaver , aspectjrt 라이브러리가 있어야 AOP 기능이 동작할 수 있으므로 build.gradle.kts일에 추가한다.

dependencies {
	...생략
	implementation("org.aspectj:aspectjweaver:1.9.19")
  	implementation("org.aspectj:aspectjrt:1.9.19")
}

 

3. AutoProxy 설정

ContextConfiguration 빈 설정 파일을 생성한다. aspectj의 autoProxy 사용에 관한 설정을 해 주어야 advice가 동작한다. proxyTargetClass=true 설정은 cglib를 이용한 프록시를 생성하는 방식인데, Spring 3.2부터 스프링 프레임워크에 포함되어 별도 라이브러리 설정을 하지 않고 사용할 수 있다. 성능 면에서 더 우수하다. 

@Configuration
@EnableAspectJAutoProxy(proxyTargetClass = true)
public class ContextConfiguration {
}

 

4. Aspect 생성

LoggingAspect 클래스를 생성하고 빈 스캐닝을 통해 빈 등록을 한다.

@Aspect : ponitcut과 advice를 하나의 클래스 단위로 정의하기 위한 어노테이션이다.

@Aspect
@Component
public class LoggingAspect {}

 

1. Pointcut

LoggingAspect 클래스에 포인트 컷을 정의한다.

@Pointcut : 여러 조인 포인트를 매치하기 위해 지정한 표현식

@Pointcut("execution(* project.aop.*Service.*(..))")
public void logPointcut() {}
  • execution 설명
  • execution은 AOP에서 가장 많이 사용되는 포인트컷 표현식 중 하나이다. execution 표현식은 메서드 실행 시점에 일치하는 조인포인트를 정의하는 데 사용된다. execution표현식의 기본 구성은 다음과 같다.
execution([접근제한자패턴] [리턴타입패턴] [클래스이름패턴] [메서드이름패턴]([파라미터타입패턴]))
  • com.example.* 패키지 내의 클래스에서 반환값이 void인 메소드 중, 메소드명이 "get*"으로 시작하는 메소드를 포함하는 표현식은 다음과 같다.
execution(void com.example.*.*.get*(..))
  • void : 리턴 타입 패턴으로 반환값이 void인 메소드를 나타낸다.
  • com.example.*.* : 클래스 이름 패턴으로 com.example 패키지 내의 모든 클래스를 나타낸다.
  • get* : 메소드 이름 패턴으로 "get"으로 시작하는 모든 메소드를 나타낸다.
  • .. : 파라미터 타입 패턴으로 모든 파라미터를 나타낸다.

com.example 패키지 내의 클래스에서 메소드명이 "set*"으로 시작하는 메소드 중, 인자로 java.lang.String 타입의 인자를 갖는 메소드를 포함하는 표현식은 다음과 같다.

execution(* com.example..set*(java.lang.String))
  • * : 리턴타입 패턴으로 모든 반환값을 나타낸다.
  • com.example.. : 클래스 이름 패턴으로 com.example 패키지 내의 모든 클래스를 나타낸다.
  • set* : 메소드 이름 패턴으로 "set"으로 시작하는 모든 메소드를 나타낸다.
  • java.lang.String : 파라미터 타입 패턴으로 인자로 java.lang.String 타입 하나만을 나타낸다.

 

2. Before

Before 어드바이스는 대상 메소드가 실행되기 이전에 실행되는 어드바이스이다. 미리 작성한 포인트 컷을 설정한다.

JoinPoint는 포인트컷으로 패치한 실행 지점이다. 매개변수로 전달한 JoinPoint 객체는 현재 조인 포인트의 메소드명, 인수값 등의 자세한 정보를 엑세스 할 수 있다.

@Before("LoggingAspect.logPointcut()")
public void logBefore(JoinPoint joinPoint) {
    System.out.println("Before joinPoint.getTarget() " + joinPoint.getTarget());
    System.out.println("Before joinPoint.getSignature() " + joinPoint.getSignature());
    if(joinPoint.getArgs().length > 0){
        System.out.println("Before joinPoint.getArgs()[0] " + joinPoint.getArgs()[0]);
    }
}

/*
=============== selectMembers ===============
Before joinPoint.getTarget() project.aop.MemberService@6ed3f258
Before joinPoint.getSignature() Map project.aop.MemberService.selectMembers()
selectMembers 메소드 실행
{1=MemberDTO(id=1, name=유관순), 2=MemberDTO(id=2, name=홍길동)}
=============== selectMember ===============
Before joinPoint.getTarget() project.aop.MemberService@6ed3f258
Before joinPoint.getSignature() 
MemberDTO project.aop.MemberService.selectMember(Long)
Before joinPoint.getArgs()[0] 3
selectMember 메소드 실행
Exception in thread "main" java.lang.RuntimeException: 해당하는 id의 회원이 없습니다.
...생략
*/

MemberService 클래스의 selectMembers 메소드와 selectMember 메소드가 실행 되기 전 Before어드바이스의 실행 내용이 삽입 되어 동작하는 것을 확인할 수 있다.

 

3. After

After 어드바이스는 대상 메소드가 실행된 이후에(정상, 예외 관계없이) 실행되는 어드바이스이다. 미리 작성한 포인트 컷을 설정한다. 포인트 컷을 동일한 클래스 내에서 사용하는 것이면 클래스명은 생략 가능하다. 단, 패키지가 다르면 패키지를 포함한 클래스명을 기술해야 한다.

Before 어드바이스와 동일하게 매개변수로 JoinPoint 객체를 전달 받을 수 있다.

@After("logPointcut()")
public void logAfter(JoinPoint joinPoint) {
    System.out.println("After joinPoint.getTarget() " + joinPoint.getTarget());
    System.out.println("After joinPoint.getSignature() " + joinPoint.getSignature());
    if(joinPoint.getArgs().length > 0){
        System.out.println("After joinPoint.getArgs()[0] " + joinPoint.getArgs()[0]);
    }
}

/*
=============== selectMembers ===============
Before joinPoint.getTarget() com.ohgiraffers.section01.aop.MemberService@5443d039
Before joinPoint.getSignature() Map com.ohgiraffers.section01.aop.MemberService.selectMembers()
selectMembers 메소드 실행
After joinPoint.getTarget() com.ohgiraffers.section01.aop.MemberService@5443d039
After joinPoint.getSignature() Map com.ohgiraffers.section01.aop.MemberService.selectMembers()
{1=MemberDTO(id=1, name=유관순), 2=MemberDTO(id=2, name=홍길동)}
=============== selectMember ===============
Before joinPoint.getTarget() com.ohgiraffers.section01.aop.MemberService@5443d039
Before joinPoint.getSignature() 
MemberDTO com.ohgiraffers.section01.aop.MemberService.selectMember(Long)
Before joinPoint.getArgs()[0] 3
selectMember 메소드 실행
After joinPoint.getTarget() com.ohgiraffers.section01.aop.MemberService@5443d039
After joinPoint.getSignature() 
MemberDTO com.ohgiraffers.section01.aop.MemberService.selectMember(Long)
After joinPoint.getArgs()[0] 3
Exception in thread "main" java.lang.RuntimeException: 해당하는 id의 회원이 없습니다.
...생략
*/

MemberService 클래스의 selectMembers 메소드와 selectMember 메소드가 실행 된 후에 After 어드바이스의 실행 내용이 삽입 되어 동작하는 것을 확인할 수 있다. Exception생 여부와 무관하게 항상 실행된다.

 

4. AfterReturing

AfterReturning 어드바이스는 대상 메소드가 정상적으로 실행된 이후에 실행되는 어드바이스이다. 미리 작성한 포인트 컷을 설정한다.

returning 속성은 리턴값으로 받아올 오브젝트의 매개변수 이름과 동일해야 한다. 또한 joinPoint는 반드시 첫 번째 매개변수로 선언해야 한다. 이 어드바이스에서는 반환 값을 가공할 수도 있다.

@AfterReturning(pointcut="logPointcut()", returning="result")
public void logAfterReturning(JoinPoint joinPoint, Object result) {
    System.out.println("After Returning result " + result);
    /* 리턴할 결과값을 변경해 줄 수 도 있다. */
    if(result != null && result instanceof Map) {
        ((Map<Long, MemberDTO>) result).put(100L, new MemberDTO(100L, "반환 값 가공"));
    }
}

/*
=============== selectMembers ===============
Before joinPoint.getTarget() project.aop.MemberService@2a62b5bc
Before joinPoint.getSignature() Map project.aop.MemberService.selectMembers()
selectMembers 메소드 실행
After Returning result {1=MemberDTO(id=1, name=유관순), 2=MemberDTO(id=2, name=홍길동)}
After joinPoint.getTarget() project.aop.MemberService@2a62b5bc
After joinPoint.getSignature() Map project.aop.MemberService.selectMembers()
{1=MemberDTO(id=1, name=유관순), 2=MemberDTO(id=2, name=홍길동), 
100=MemberDTO(id=100, name=반환 값 가공)}
=============== selectMember ===============
Before joinPoint.getTarget() project.aop.MemberService@2a62b5bc
Before joinPoint.getSignature() 
MemberDTO project.aop.MemberService.selectMember(Long)
Before joinPoint.getArgs()[0] 3
selectMember 메소드 실행
After joinPoint.getTarget() project.aop.MemberService@2a62b5bc
After joinPoint.getSignature() 
MemberDTO project.aop.MemberService.selectMember(Long)
After joinPoint.getArgs()[0] 3
Exception in thread "main" java.lang.RuntimeException: 해당하는 id의 회원이 없습니다.
...생략
*/

MemberService 클래스의 selectMembers 메소드가 실행 된 후에 AfterReturning 어드바이스의 실행 내용이 삽입 되어 동작하는 것을 확인할 수 있다. Exception 이 발생한 selectMember메소드에서는 동작하지 않는다.

 

5. AfterThrowing

AfterThrowing 어드바이스는 예외가 발생했을 때 실행되는 어드바이스이다. 미리 작성한 포인트 컷을 설정한다.

throwing 속성의 이름과 매개변수의 이름이 동일해야 한다. 이 어드바이스에서는 Exception 에 따른 처리를 작성할 수 있다.

@AfterThrowing(pointcut="logPointcut()", throwing="exception")
public void logAfterThrowing(Throwable exception) {
    System.out.println("After Throwing exception " + exception);
}

/*
=============== selectMembers ===============
Before joinPoint.getTarget() project.aop.MemberService@24111ef1
Before joinPoint.getSignature() Map project.aop.MemberService.selectMembers()
selectMembers 메소드 실행
After Returning result {1=MemberDTO(id=1, name=유관순), 2=MemberDTO(id=2, name=홍길동)}
After joinPoint.getTarget() project.aop.MemberService@24111ef1
After joinPoint.getSignature() Map project.aop.MemberService.selectMembers()
{1=MemberDTO(id=1, name=유관순), 2=MemberDTO(id=2, name=홍길동), 
100=MemberDTO(id=100, name=반환 값 가공)}
=============== selectMember ===============
Before joinPoint.getTarget() project.aop.MemberService@24111ef1
Before joinPoint.getSignature() 
MemberDTO project.aop.MemberService.selectMember(Long)
Before joinPoint.getArgs()[0] 3
selectMember 메소드 실행
After Throwing exception java.lang.RuntimeException: 해당하는 id의 회원이 없습니다.
After joinPoint.getTarget() project.aop.MemberService@24111ef1
After joinPoint.getSignature() 
MemberDTO project.aop.MemberService.selectMember(Long)
After joinPoint.getArgs()[0] 3
Exception in thread "main" java.lang.RuntimeException: 해당하는 id의 회원이 없습니다.
...생략
*/

MemberService 클래스의 selectMember 메소드가 실행 된 후에 AfterThrowing 어드바이스의 실행 내용이 삽입 되어 동작하는 것을 확인할 수 있다. Exception 이 발생하지 않은 selectMembers 메소드에서는 동작하지 않는다.

 

6. Around

Around 어드바이스는 대상 메소드 실행 전/후에 적용되는 어드바이스이다. 미리 작성한 포인트 컷을 설정한다.

Around Advice는 가장 강력한 어드바이스이다. 이 어드바이스는 조인포인트를 완전히 장악하기 때문에 앞에 살펴 본 어드바이스 모두 Around 어드바이스로 조합할 수 있다.

AroundAdvice의 조인포인트 매개변수는 ProceedingJoinPoint로 고정되어 있다. JoinPoint의 하위 인터페이스로 원본 조인포인트의 진행 시점을 제어할 수 있다.

조인포인트 진행하는 호출을 잊는 경우가 자주 발생하기 때문에 주의해야 하며 최소한의 요건을 충족하면서도 가장 기능이 약한 어드바이스를 쓰는게 바람직하다.

@Around("logPointcut()")
public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
    System.out.println("Around Before " + joinPoint.getSignature().getName());
    /* 원본 조인포인트를 실행한다. */
    Object result = joinPoint.proceed();
    System.out.println("Around After " + joinPoint.getSignature().getName());
    /* 원본 조인포인트를 호출한 쪽 혹은 다른 어드바이스가 다시 실행할 수 있도록 반환한다. */
    return result;
}

/*
=============== selectMembers ===============
Around Before selectMembers
Before joinPoint.getTarget() project.aop.MemberService@21a21c64
Before joinPoint.getSignature() Map project.aop.MemberService.selectMembers()
selectMembers 메소드 실행
After Returning result {1=MemberDTO(id=1, name=유관순), 2=MemberDTO(id=2, name=홍길동)}
After joinPoint.getTarget() project.aop.MemberService@21a21c64
After joinPoint.getSignature() Map project.aop.MemberService.selectMembers()
Around After selectMembers
{1=MemberDTO(id=1, name=유관순), 2=MemberDTO(id=2, name=홍길동), 
100=MemberDTO(id=100, name=반환 값 가공)}
=============== selectMember ===============
Around Before selectMember
Before joinPoint.getTarget() project.aop.MemberService@21a21c64
Before joinPoint.getSignature() 
MemberDTO project.aop.MemberService.selectMember(Long)
Before joinPoint.getArgs()[0] 3
selectMember 메소드 실행
After Throwing exception java.lang.RuntimeException: 해당하는 id의 회원이 없습니다.
After joinPoint.getTarget() project.aop.MemberService@21a21c64
After joinPoint.getSignature() 
MemberDTO project.aop.MemberService.selectMember(Long)
After joinPoint.getArgs()[0] 3
Exception in thread "main" java.lang.RuntimeException: 해당하는 id의 회원이 없습니다.
...생략
*/

MemberService 클래스의 selectMember 메소드가 실행 된 후에 AfterThrowing 어드바이스의 실행 내용이 삽입 되어 동작하는 것을 확인할 수 있다. Exception 이 발생하지 않은 selectMembers소드에서는 동작하지 않는다.

728x90
반응형
728x90
반응형

[Spring Framework] 초보자를 위한 Spring Bean Properties 가이드

 

[Spring Framework] 초보자를 위한 Spring Bean Properties 가이드

[Spring Framework] Spring Boot Bean 초기화(init)와 소멸(destroy) 메서드 완전 정리 [Spring Framework] Spring Boot Bean 초기화(init)와 소멸(destroy) 메서드 완전 정리[Spring Framework] Spring Bean Scope 완벽 가이드 | Singleton

crushed-taro.tistory.com

1. AOP

1. AOP란?

AOP는 관점 지향 프로그래밍(Aspect Oriented Programming)의 약자이다. 중복되는 공통 코드를 분리하고 코드 실행 전이나 후의 시점에 해당 코드를 삽입함으로써 소스 코드의 중복을 줄이고, 필요할 때마다 가져다 쓸 수 있게 객체화하는 기술을 말한다.

AOP 사진 1

 

2. AOP 핵심 용어

용어 설명
Aspect 핵심 비즈니스 로직과는 별도로 수행되는 횡단 관심사를 말한다.
Advice Aspect의 기능 자체를 말한다.
Join point Advice가 적용될 수 있는 위치를 말한다.
Pointcut Join point 중에서 Advice가 적용될 가능성이 있는 부분을 선별한 것을 말한다.
Weaving Advice를 핵심 비즈니스 로직에 적용하는 것을 말한다.

AOP 사진 2

 

3. Advice의 종류

종류 설명
Before 대상 메소드가 실행되기 이전에 실행되는 어드바이스
After-returning 대상 메소드가 정상적으로 실행된 이후에 실행되는 어드바이스
After-throwing 예외가 발생했을 때 실행되는 어드바이스
After 대상 메소드가 실행된 이후에(정상, 예외 관계없이) 실행되는 어드바이스
Around 대상 메소드 실행 전/후에 적용되는 어드바이스

 

4. Spring AOP

스프링 프레임워크에서 제공하는 AOP는 다음과 같은 특징을 가진다.

  • 프록시 기반의 AOP 구현체 : 대상 객체(Target Object)에 대한 프록시를 만들어 제공하며, 타겟을 감싸는 프록시는 서버 Runtime 시에 생성된다.
  • 메서드 조인 포인트만 제공 : 핵심기능(대상 객체)의 메소드가 호출되는 런타임 시점에만 부가기능(어드바이스)을 적용할 수 있다.

AOP 사진 3

728x90
반응형
728x90
반응형

[Spring Framework] Spring Boot Bean 초기화(init)와 소멸(destroy) 메서드 완전 정리

 

[Spring Framework] Spring Boot Bean 초기화(init)와 소멸(destroy) 메서드 완전 정리

[Spring Framework] Spring Bean Scope 완벽 가이드 | Singleton부터 Prototype까지 [Spring Framework] Spring Bean Scope 완벽 가이드 | Singleton부터 Prototype까지[Spring Framework] Spring Framework에서 @Inject 애너테이션 완벽 가이

crushed-taro.tistory.com

1. Bean

1. Properties

1. Properties

Properties는 키/값 쌍으로 이루어진 간단한 파일이다. 보통 소프트웨어 설정 정보를 저장할 때 사용된다. 스프링에서는 Properties를 이용하여 빈의 속성 값을 저장하고 읽어올 수 있다.

Properties 파일의 각 줄은 다음과 같은 형식으로 구성된다. 주석은#으로 시작하며, 빈 줄은 무시된다.

# 주석
key=value

product-info.properties라는 이름의 파일을 생성하고 Product 타입의 값이 될 value를 적절한 key를 설정하여 정의한다.

bread.carpbread.name=붕어빵
bread.carpbread.price=1000
beverage.milk.name=딸기우유
beverage.milk.price=1500
beverage.milk.capacity=500
beverage.water.name=지리산암반수
beverage.water.price=3000
beverage.water.capacity=500
bread.carpBread.name=\uBD95\uC5B4\uBE75
bread.carpBread.price=800
beverage.milk.name=\uC544\uBAAC\uB4DC\uC6B0\uC720
beverage.milk.price=2800
beverage.milk.capacity=950
beverage.water.name=\uC0BC\uB2E4\uC218
beverage.water.price=1000
beverage.water.capacity=2000

상품들을 빈으로 등록할 설정 파일을 작성한다. 이 때product-info.properties 파일에 기재한 값으로 상품들의 값을 초기화 하려고 한다. properties 파일을 읽어올 때 @PropertySource 어노테이션에 경로를 기재하여 읽어올 수 있으므로 읽어올 properties 파일의 경로를 작성한다.

@Configuration
/* resources 폴더 하위 경로를 기술한다. 폴더의 구분은 슬러쉬(/) 혹은 역슬러쉬(\\)로 한다. */
@PropertySource("properties/product-info.properties")
public class ContextConfiguration {

}

빈 설정 파일 내부에@Value 어노테이션을 사용하여 properties의 값을 읽어온다. @Value어노테이션은 빈의 속성 값을 자동으로 주입받을 수 있는 어노테이션이다.

@Configuration
/* resources 폴더 하위 경로를 기술한다. 폴더의 구분은 슬러쉬(/) 혹은 역슬러쉬(\\)로 한다. */
@PropertySource("properties/product-info.properties")
public class ContextConfiguration {

	/* 치환자(placeholder) 문법을 이용하여 properties에 저장된 key를 입력하면 value에 해당하는 값을 꺼내온다.
   * 공백을 사용하면 값을 읽어오지 못하니 주의한다.
   * : 을 사용하면 값을 읽어오지 못하는 경우 사용할 대체 값을 작성할 수 있다.
   **/
	@Value("${bread.carpbread.name:팥붕어빵}")
	private String carpBreadName;

	/* 값은 여러 번 불러올 수 있다. */
//	@Value("${bread.carpbread.name:슈크림붕어빵}")
//	private String carpBreadName2;

  @Value("${bread.carpbread.price:0}")
  private int carpBreadPrice;

  @Value("${beverage.milk.name:}")
  private String milkName;

  @Value("${beverage.milk.price:0}")
  private int milkPrice;

  @Value("${beverage.milk.capacity:0}")
  private int milkCapacity;

  @Bean
  public Product carpBread() {

      return new Bread(carpBreadName, carpBreadPrice, new java.util.Date());
  }

  @Bean
  public Product milk() {

      return new Beverage(milkName, milkPrice, milkCapacity);
  }

  @Bean
  public Product water(@Value("${beverage.water.name:}") String waterName,
                       @Value("${beverage.water.price:0}") int waterPrice,
                       @Value("${beverage.water.capacity:0}") int waterCapacity) {

      return new Beverage(waterName, waterPrice, waterCapacity);
  }

  @Bean
  @Scope("prototype")
  public ShoppingCart cart() {

      return new ShoppingCart();
  }
}

필드 또는 파라미터에@Value 어노테이션을 사용할 수 있으며 해당 어노테이션에 ${key} 와 같이 치환자(placeholder) 문법을 이용하여 properties에 저장된 key를 입력하면 value에 해당하는 값을 꺼내와 필드 또는 파라미터에 주입한다. key 뒤에 :을 이용하여 해당 key 값이 없을 경우에는 주입할 기본 값을 입력할 수 있다.

/* 빈 설정 파일을 기반으로 IoC 컨테이너 생성 */
ApplicationContext context = new AnnotationConfigApplicationContext(ContextConfiguration.class);

...생략

/*
cart1에 담긴 내용 : [붕어빵 1000 Thu Jun 08 23:07:58 KST 2023, 딸기우유 1500 500]
cart2에 담긴 내용 : [지리산암반수 3000 500]
cart1의 hashcode : 716487794
cart2의 hashcode : 987249254
*/

해당 빈 설정 파일을 읽어 IoC 컨테이너를 생성하고 컨테이너에서 상품 객체들을 꺼내 쇼핑 카트에 담아 출력하는 코드를 실행해보면Properties파일의 값이 잘 주입 된 것을 확인할 수 있다.

 

2. 국제화

국제화(Internationalization 또는 i18n)란, 소프트웨어를 다양한 언어와 문화권에 맞게 번역할 수 있도록 디자인하는 과정이다. Spring Framework에서 i18n은 MessageSource 인터페이스와 property 파일을 이용하여 구현된다. 각 언어별로 property 파일을 정의하면, Spring은 사용자의 로케일에 맞게 적절한 파일을 선택하여 애플리케이션 텍스트를 올바르게 번역할 수 있다.

먼저 resources 폴더에 한국어 와 영어 버전의 에러 메세지를 properties 파일로 정의한다. properties 파일에 {인덱스} 의 형식으로 문자를 입력하면 값을 전달하면서 value를 불러올 수 있다. 각 파일의 끝에는 Locale 이 적절하게 입력 되어야 한다. 다음은 일반적으로 사용되는 Locale코드들의 목록이다.

언어 국가 코드
한국어 대한민국 ko_KR
영어 미국 en_US
영어 영국 en_UK
일본어 일본 ja_JP
스페인어 스페인 es_ES
# 한국어 버전
# message_ko_KR.properties
error.404=페이지를 찾을 수 없습니다!
error.500=개발자의 잘못입니다. 개발자는 누구? {0} 입니다. 현재시간 {1}
# 영어 버전
# message_en_US.properties
error.404=Page Not Found!!
error.500=something wrong! The developer''s fault. who is devloper? It''s {0} at {1}

빈 설정 파일에MessageSource 타입의 빈을 등록한다. 지정 된 명칭이므로 컨테이너에 등록 되는 빈 이름(메소드명)을 정확하게 작성하도록 한다.

@Configuration
public class ContextConfiguration {
	
	@Bean
	public ReloadableResourceBundleMessageSource messageSource() {
		
		/* 접속하는 세션의 로케일에 따라 자동 재로딩하는 용도의 MessageSource 구현체 */
		ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
		
		/* 다국어메세지를 읽어올 properties 파일의 파일 이름을 설정한다. */
		messageSource.setBasename("properties/subsection02/i18n/message");
		/* 불러온 메세지를 해당 시간 동안 캐싱한다. */
		messageSource.setCacheSeconds(10);
		/* 기본 인코딩 셋을 설정할 수 있다. */
		messageSource.setDefaultEncoding("UTF-8");
		
		return messageSource;
	}
}

ReloadableResourceBundleMessageSource 은 MessageSource 인터페이스의 구현체 중 한 종류로 접속하는 세션의 로케일에 따라 자동 재로딩하는 기능을 가지고 있다. basename 속성에 다국어 메세지를 읽어올 properties 파일의 이름을 설정한다. 그 외에도 MessageSource에 대해 다양한 설정을 할 수 있다.

ApplicationContext context = new AnnotationConfigApplicationContext(ContextConfiguration.class);

String error404MessageKR = context.getMessage("error.404", null, Locale.KOREA);
String error500MessageKR = context.getMessage("error.500", 
	new Object[] {"여러분", new Date()}, Locale.KOREA);

System.out.println("I18N error.404 메세지 : " + error404MessageKR);
System.out.println("I18N error.500 메세지  : " + error500MessageKR);

/*
I18N error.404 메세지 : 페이지를 찾을 수 없습니다!
I18N error.500 메세지 : 개발자의 잘못입니다. 개발자는 누구? 여러분 입니다. 현재시간 23. 6. 8. 오후 11:31
*/

빈 설정 파일을 읽어와 IoC 컨테이너를 구동시키고getMessage 메소드를 통해 읽어올 메세지의 key 값과 Locale.KOREA 라고 하는 Locale을 전달한다. ReloadableResourceBundleMessageSource 가 기능하여 한국어 메세지를 로드해오는 것을 출력을 통해 확인할 수 있다. 이 때 getMessage 메소드의 두 번째 인자는 전달 값으로 배열로 전달 시 properties 파일에 {인덱스} 로 작성했던 영역에 인덱스 순서대로 채워지는 것을 확인할 수 있다.

ApplicationContext context = new AnnotationConfigApplicationContext(ContextConfiguration.class);

String error404MessageUS = context.getMessage("error.404", null, Locale.US);
String error500MessageUS = context.getMessage("error.500", 
	new Object[] {"you", new Date()}, Locale.US);
		
System.out.println("The I18N message for error.404 : " + error404MessageUS);
System.out.println("The I18N message for error.500 : " + error500MessageUS);

/*
The I18N message for error.404 : Page Not Found!!
The I18N message for error.500 : something wrong! The developer's fault. who is devloper? 
It's you at 6/8/23, 11:31 PM
*/

다시 한 번 빈 설정 파일을 읽어와 IoC 컨테이너를 구동시키고getMessage 메소드를 통해 읽어올 메세지의 key 값과  Locale.US 라고 하는 Locale을 전달한다. ReloadableResourceBundleMessageSource 가 기능하여 영어 메세지를 로드해오는 것을 출력을 통해 확인할 수 있다. getMessage메소드의 두 번째 인자로 전달 된 값도 함께 잘 출력 되는 것을 확인할 수 있다.

728x90
반응형
728x90
반응형

[Spring Framework] Spring Bean Scope 완벽 가이드 | Singleton부터 Prototype까지

 

[Spring Framework] Spring Bean Scope 완벽 가이드 | Singleton부터 Prototype까지

[Spring Framework] Spring Framework에서 @Inject 애너테이션 완벽 가이드 [Spring Framework] Spring Framework에서 @Inject 애너테이션 완벽 가이드[Spring Framework] Spring Boot DI 완벽 정리 | @Resource 활용법 [Spring Framework] Sp

crushed-taro.tistory.com

1. Bean

1. init, destroy method

스프링 빈은 초기화(init)와 소멸화(destroy)의 라이프 사이클을 가지고 있다. 이 라이프 사이클을 이해하면 빈 객체가 생성되고 소멸될 때 추가적인 작업을 수행할 수 있다. 

init-method 속성을 사용하면 스프링이 빈 객체를 생성한 다음 초기화 작업을 수행할 메소드를 지정할 수 있다. 이 메소드는 빈 객체 생성자가 완료된 이후에 호출된다. init-method 속성으로 지정된 메소드는 일반적으로 빈의 초기화를 위해 사용된다.

destroy-method 속성을 사용하면 빈 객체가 소멸될 때 호출할 메소드를 지정할 수 있다. 이 메소드는 ApplicationContext의 close() 메소드가 호출되기 전에 빈 객체가 소멸될 때 호출된다. destroy-method 속성으로 지정 된 메소드는 일반적으로 사용하던 리소스를 반환하기 위해 사용된다.

 

1. java

java 설정 방식으로init-methoddestroy-method 를 테스트 하기 위해 Owner라는 클래스를 추가한다.

public class Owner {
	
	public void openShop() {
		System.out.println("사장님이 가게 문을 열었습니다. 이제 쇼핑을 하실 수 있습니다.");
	}
	
	public void closeShop() {
		System.out.println("사장님이 가게 문을 닫았습니다. 이제 쇼핑을 하실 수 없습니다.");
	}
	
}

 

Owner 타입의 빈 객체를 설정 파일에 등록한다. @Bean 어노테이션에는 initMethoddestoryMethod 라는 속성이 있는데 해당 속성을 Owner 클래스에 정의했던 openShopcloseShop메소드로 설정한다.

@Configuration
public class ContextConfiguration {
	
	...생략
	
	/* init-method로 openShop 메소드를 설정하고 destory-method로 closeShope 메소드를 설정한다. */
	@Bean(initMethod = "openShop", destroyMethod="closeShop")
	public Owner owner() {
		
		return new Owner()
	}

}

 

실행 파일에서 빈 설정 파일을 기반으로 IoC 컨테이너를 생성하고 쇼핑 카트에 상품을 담는 동일한 코드의 끝에 컨테이너를 종료하는 코드를 추가하여 실행해본다.

/* 빈 설정 파일을 기반으로 IoC 컨테이너 생성 */
ApplicationContext context = new AnnotationConfigApplicationContext(ContextConfiguration.class);

...생략

/* init 메소드는 빈 객체 생성 시점에 동작하므로 바로 확인할 수 있지만
 * destroy 메소드는 빈 객체 소멸 시점에 동작하므로 컨테이너가 종료 되지 않을 경우 확인할 수 없다.
 * 가비지 컬렉터가 해당 빈을 메모리에서 지울 때 destroy 메소드가 동작하게 되는데 
 * 메모리에서 지우기 전에 프로세스는 종료되기 때문이다.
 * 따라서 아래와 같이 강제로 컨테이너를 종료시키면 destroy 메소드가 동작할 것이다.
 * */
((AnnotationConfigApplicationContext) context).close();

/*
사장님이 가게 문을 열었습니다. 이제 쇼핑을 하실 수 있습니다.
cart1에 담긴 내용 : [붕어빵 1000 Thu Jun 08 21:58:53 KST 2023, 딸기우유 1500 500]
cart2에 담긴 내용 : [지리산암반수 3000 500]
사장님이 가게 문을 닫았습니다. 이제 쇼핑을 하실 수 없습니다.
*/

 

openShop 메소드가 Owner 객체의 생성 시점에 호출 되고, closeShop 메소드가 Owner객체의 소멸 시점에 호출 되었음을 확인할 수 있다. init 메소드는 빈 객체 생성 시점에 동작하므로 바로 확인할 수 있지만 destroy 메소드는 빈 객체 소멸 시점에 동작하므로 컨테이너가 종료 되지 않을 경우 확인할 수 없다. 따라서 컨테이너를 종료시키면 destroy 메소드의 동작까지 확인 할 수 있다.

 

2. annotation

annotation 방식으로init-method,destroy-method를 테스트 하기 위해Owner라는 클래스를 추가한다.

@Component
public class Owner {
	
	/* init-method와 같은 설정 어노테이션이다. */
	@PostConstruct
	public void openShop() {
		System.out.println("사장님이 가게 문을 오픈하셨습니다. 이제 쇼핑을 하실 수 있습니다.");
	}
	
	/* destroy-method와 같은 설정 어노테이션이다. */
	@PreDestroy
	public void closeShop() {
		System.out.println("사장님이 가게 문을 닫으셨습니다. 이제 쇼핑을 하실 수 없습니다.");
	}
	
}

컴포넌트 스캔을 통해 빈 등록 하기 위해 @Componet 어노테이션을 클래스 위에 설정한다. javax.annotation의 @PostConstruct , @PreDestroy 어노테이션은 @Bean 어노테이션에 init-methoddestroy-method 속성을 설정하는 것과 같은 역할을 한다. 단, 해당 어노테이션을 사용할 수 있도록 라이브러리 의존성이 build.gradle.kts파일에 추가 되어 있어야 한다.

dependencies {
	...생략
	implementation("javax.annotation:javax.annotation-api:1.3.2")
}

Owner타입의 빈 객체를 컴포넌트 스캔을 통해 읽어 등록할 수 있도록 빈 설정 파일에 컴포넌트 스캔 경로를 설정한다. 그 외의 상품과 쇼핑 카트의 빈 등록 코드는 그대로 사용한다.

@Configuration
@ComponentScan("project.initdestroy.subsection02.annotation")
public class ContextConfiguration {
	...생략
}

실행 파일에서 빈 설정 파일을 기반으로 IoC 컨테이너를 생성하고 쇼핑 카트에 상품을 담는 동일한 코드의 끝에 컨테이너를 종료하는 코드를 추가하여 실행해본다.

/* 빈 설정 파일을 기반으로 IoC 컨테이너 생성 */
ApplicationContext context = new AnnotationConfigApplicationContext(ContextConfiguration.class);

...생략

/* init 메소드는 빈 객체 생성 시점에 동작하므로 바로 확인할 수 있지만
 * destroy 메소드는 빈 객체 소멸 시점에 동작하므로 컨테이너가 종료 되지 않을 경우 확인할 수 없다.
 * 가비지 컬렉터가 해당 빈을 메모리에서 지울 때 destroy 메소드가 동작하게 되는데 메모리에서 지우기 전에 프로세스는 종료되기 때문이다.
 * 따라서 아래와 같이 강제로 컨테이너를 종료시키면 destroy 메소드가 동작할 것이다.
 * */
((AnnotationConfigApplicationContext) context).close();

/*
사장님이 가게 문을 열었습니다. 이제 쇼핑을 하실 수 있습니다.
cart1에 담긴 내용 : [붕어빵 1000 Thu Jun 08 21:59:07 KST 2023, 딸기우유 1500 500]
cart2에 담긴 내용 : [지리산암반수 3000 500]
사장님이 가게 문을 닫았습니다. 이제 쇼핑을 하실 수 없습니다.
*/

openShop 메소드가 Owner 객체의 생성 시점에 호출 되고, closeShop 메소드가 Owner 객체의 소멸 시점에 호출 되었음을 확인할 수 있다. 

 

3. xml

xml 설정 방식으init-methoddestroy-method 를 테스트 하기 위해 Owner라는 클래스를 추가한다.

public class Owner {
	
	public void openShop() {
		System.out.println("사장님이 가게 문을 열었습니다. 이제 쇼핑을 하실 수 있습니다.");
	}
	
	public void closeShop() {
		System.out.println("사장님이 가게 문을 닫았습니다. 이제 쇼핑을 하실 수 없습니다.");
	}
	
}

bean configuration file에<bean> 태그를 통해 상품, 쇼핑카트 그리고 Owener 에 대한 빈 등록을 설정한다.Owener 에는 init-methoddestroy-method 설정한다.

<?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="carpBread" class="project.common.Bread">
		<constructor-arg name="name" value="붕어빵"/>
		<constructor-arg name="price" value="1000"/>
		<constructor-arg name="bakedDate" ref="today"/>
	</bean>
	
	<bean id="today" class="java.util.Date" scope="prototype"/>
	
	<bean id="milk" class="project.common.Beverage">
		<constructor-arg name="name" value="딸기우유"/>
		<constructor-arg name="price" value="1500"/>
		<constructor-arg name="capacity" value="500"/>
	</bean>
	
	<bean id="water" class="project.common.Beverage">
		<constructor-arg name="name" value="지리산암반수"/>
		<constructor-arg name="price" value="3000"/>
		<constructor-arg name="capacity" value="500"/>
	</bean>
	
	<bean id="cart" class="project.common.ShoppingCart" scope="prototype"/>

	<bean id="owner" class="project.section02.initdestroy.subsection03.xml.Owner" 
			  init-method="openShop" destroy-method="closeShop"/>
</beans>

실행 파일에서 빈 설정 파일을 기반으로 IoC 컨테이너를 생성하고 쇼핑 카트에 상품을 담는 동일한 코드의 끝에 컨테이너를 종료하는 코드를 추가하여 실행해본다.

/* 빈 설정 파일을 기반으로 IoC 컨테이너 생성 */
ApplicationContext context 
	= new GenericXmlApplicationContext("section02/initdestroy/subsection03/xml/spring-context.xml");

...생략

/* init 메소드는 빈 객체 생성 시점에 동작하므로 바로 확인할 수 있지만
 * destroy 메소드는 빈 객체 소멸 시점에 동작하므로 컨테이너가 종료 되지 않을 경우 확인할 수 없다.
 * 가비지 컬렉터가 해당 빈을 메모리에서 지울 때 destroy 메소드가 동작하게 되는데 
 * 메모리에서 지우기 전에 프로세스는 종료되기 때문이다.
 * 따라서 아래와 같이 강제로 컨테이너를 종료시키면 destroy 메소드가 동작할 것이다.
 * */
((GenericXmlApplicationContext) context).close();

/*
사장님이 가게 문을 열었습니다. 이제 쇼핑을 하실 수 있습니다.
cart1에 담긴 내용 : [붕어빵 1000 Thu Jun 08 22:00:09 KST 2023, 딸기우유 1500 500]
cart2에 담긴 내용 : [지리산암반수 3000 500]
사장님이 가게 문을 닫았습니다. 이제 쇼핑을 하실 수 없습니다.
*/

openShop 메소드가 Owner 객체의 생성 시점에 호출 되고, closeShop 메소드가 Owner 객체의 소멸 시점에 호출 되었음을 확인할 수 있다. 

728x90
반응형
728x90
반응형

[Spring Framework] Spring Framework에서 @Inject 애너테이션 완벽 가이드

 

[Spring Framework] Spring Framework에서 @Inject 애너테이션 완벽 가이드

[Spring Framework] Spring Boot DI 완벽 정리 | @Resource 활용법 [Spring Framework] Spring Boot DI 완벽 정리 | @Resource 활용법[Spring Framework] Spring Boot DI 핵심 가이드 | @Primary와 @Qualifier 제대로 이해하기 [Spring Framework]

crushed-taro.tistory.com

1. Bean

아래 코드는 이번 차시의 테스트에 공통적으로 사용할 Product , Beverage , Bread , ShoppingCart 클래스이다.

 

  • Product(abstract class)
public abstract class Product {
	
	private String name;	//상품명
	private int price;		//상품가격
	
	public Product() {}

	public Product(String name, int price) {
		super();
		this.name = name;
		this.price = price;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getPrice() {
		return price;
	}

	public void setPrice(int price) {
		this.price = price;
	}

 

  • Beverage
public class Beverage extends Product {
	
	private int capacity;	//용량
	
	public Beverage() {
		super();
	}
	
	public Beverage(String name, int price, int capacity) {
		super(name, price);
		this.capacity = capacity;
	}
	
	public int getCapacity() {
		return this.capacity;
	}
	
	public void setCapacity(int capacity) {
		this.capacity = capacity;
	}
	
	@Override
	public String toString() {
		return super.toString() + " " + this.capacity;
	}
}

 

  • Bread
public class Bread extends Product {
	
	private java.util.Date bakedDate;	//생산시간
	
	public Bread() {
		super();
	}
	
	public Bread(String name, int price, java.util.Date bakedDate) {
		super(name, price);
		this.bakedDate = bakedDate;
	}
	
	public java.util.Date getBakedDate() {
		return this.bakedDate;
	}
	
	public void setBakedDate(java.util.Date bakedDate) {
		this.bakedDate = bakedDate;
	}
	
	@Override
	public String toString() {
		return super.toString() + " " + this.bakedDate;
	}
}

 

  • ShoppingCart
public class ShoppingCart {
	
	private final List<Product> items;	//쇼핑카트에 담긴 상품들
	
	public ShoppingCart() {
		items = new ArrayList<>();
	}
	
	public void addItem(Product item) {
		items.add(item);
	}
	
	public List<Product> getItem() {
		return items;
	}
}

 

1. Bean Scope

bean scope란, 스프링 빈이 생성될 때 생성되는 인스턴스의 범위를 의미한다. 스프링에서는 다양한 bean scope를 제공한다.

Bean Scope Description
Singleton 하나의 인스턴스만을 생성하고, 모든 빈이 해당 인스턴스를 공유하여 사용한다.
Prototype 매번 새로운 인스턴스를 생성한다.
Request HTTP 요청을 처리할 때마다 새로운 인스턴스를 생성하고, 요청 처리가 끝나면 인스턴스를 폐기한다. 웹 애플리케이션 컨텍스트에만 해당된다.
Session HTTP 세션 당 하나의 인스턴스를 생성하고, 세션이 종료되면 인스턴스를 폐기한다. 웹 애플리케이션 컨텍스트에만 해당된다.

 

1. singleton

Spring Framework에서 Bean의 기본 스코프는 singleton이다. singleton은 애플리케이션 내에서 하나의 인스턴스만을 생성하고, 모든 빈이 해당 인스턴스를 공유하여 사용한다. 이를 통해 메모리 사용량을 줄일 수 있으며, 성능 향상을 기대할 수 있다.

 

@Configuration
public class ContextConfiguration {
	
	@Bean
	public Product carpBread() {
		
		return new Bread("붕어빵", 1000, new java.util.Date());
	}
	
	@Bean
	public Product milk() {
		
		return new Beverage("딸기우유", 1500, 500);
	}
	
	@Bean
	public Product water() {
		
		return new Beverage("지리산암반수", 3000, 500);
	}
	
	@Bean
	@Scope("singleton")		//기본값
	public ShoppingCart cart() {
		
		return new ShoppingCart();
	}
}

ContextConfiguration 설정 파일에Bread 타입의 붕어빵과 Beaverage 타입의 딸기우유와 지리산암반수, ShoppingCart 타입의 쇼핑카트를 bean으로 등록 한다. @Scope 어노테이션에 기본 값에 해당하는 singleton설정도 기재하였다.

 

/* 빈 설정 파일을 기반으로 IoC 컨테이너 생성 */
ApplicationContext context = new AnnotationConfigApplicationContext(ContextConfiguration.class);

/* 붕어빵, 딸기우유, 지리산 암반수 등의 빈 객체를 반환 받는다. */
Product carpBread = context.getBean("carpBread", Bread.class);
Product milk = context.getBean("milk", Beverage.class);
Product water = context.getBean("water", Beverage.class);

/* 첫 번째 손님이 쇼핑 카트를 꺼낸다. */
ShoppingCart cart1 = context.getBean("cart", ShoppingCart.class);
cart1.addItem(carpBread);
cart1.addItem(milk);

/* 붕어빵과 딸기우유가 담겨있다. */
System.out.println("cart1에 담긴 내용 : " + cart1.getItem());

/* 두 번째 손님이 쇼핑 카트를 꺼낸다. */		
ShoppingCart cart2 = context.getBean("cart", ShoppingCart.class);
cart2.addItem(water);

/* 붕어빵과 딸기우유와 지리산암반수가 담겨있다. */
System.out.println("cart2에 담긴 내용 : " + cart2.getItem());
		
/* 두 카드의 hashcode를 출력해보면 동일한 것을 볼 수 있다. */
System.out.println("cart1의 hashcode : " + cart1.hashCode());
System.out.println("cart2의 hashcode : " + cart2.hashCode());

/*
cart1에 담긴 내용 : [붕어빵 1000 Thu Jun 08 21:58:27 KST 2023, 딸기우유 1500 500]
cart2에 담긴 내용 : [붕어빵 1000 Thu Jun 08 21:58:27 KST 2023, 딸기우유 1500 500, 지리산암반수 3000 500]
cart1의 hashcode : 696933920
cart2의 hashcode : 696933920
*/

이 예제에서 손님 두 명이 각각 쇼핑 카트를 이용해 상품을 담는다고 가정했지만singleton으로 관리되는 cart는 사실 하나의 객체이므로 두 손님이 동일한 카트에 물건을 담는 상황이 발생한다. 상황에 따라서 기본 값인 singleton 스코프가 아닌 prototype 스코프가 필요할 수 있다. 

 

2. prototype

prototype 스코프를 갖는 Bean은 매번 새로운 인스턴스를 생성한다. 이를 통해 의존성 주입 등의 작업에서 객체 생성에 대한 부담을 줄일 수 있다.
@Configuration
public class ContextConfiguration {
	
	@Bean
	public Product carpBread() {
		
		return new Bread("붕어빵", 1000, new java.util.Date());
	}
	
	@Bean
	public Product milk() {
		
		return new Beverage("딸기우유", 1500, 500);
	}
	
	@Bean
	public Product water() {
		
		return new Beverage("지리산암반수", 3000, 500);
	}
	
	@Bean
	@Scope("prototype")		//기본 값에서 변경
	public ShoppingCart cart() {
		
		return new ShoppingCart();
	}

}

이전 예제와 동일하게 ContextConfiguration 설정 파일에 Bread 타입의 붕어빵과 Beaverage 타입의 딸기우유와 지리산암반수, ShoppingCart 타입의 쇼핑카트를 bean으로 등록 한다. 단, ShoppingCart의 경우 @Scope 어노테이션에 기본 값이 아닌 해당하는 prototype설정도 기재하였다.

 

/* 빈 설정 파일을 기반으로 IoC 컨테이너 생성 */
ApplicationContext context = new AnnotationConfigApplicationContext(ContextConfiguration.class);

/* 붕어빵, 딸기우유, 지리산 암반수 등의 빈 객체를 반환 받는다. */
Product carpBread = context.getBean("carpBread", Bread.class);
Product milk = context.getBean("milk", Beverage.class);
Product water = context.getBean("water", Beverage.class);

/* 첫 번째 손님이 쇼핑 카트를 꺼낸다. */
ShoppingCart cart1 = context.getBean("cart", ShoppingCart.class);
cart1.addItem(carpBread);
cart1.addItem(milk);

/* 붕어빵과 딸기우유가 담겨있다. */
System.out.println("cart1에 담긴 내용 : " + cart1.getItem());

/* 두 번째 손님이 쇼핑 카트를 꺼낸다. */		
ShoppingCart cart2 = context.getBean("cart", ShoppingCart.class);
cart2.addItem(water);

/* 지리산암반수가 담겨있다. */
System.out.println("cart2에 담긴 내용 : " + cart2.getItem());
		
/* 두 카드의 hashcode를 출력해보면 다른 것을 볼 수 있다. */
System.out.println("cart1의 hashcode : " + cart1.hashCode());
System.out.println("cart2의 hashcode : " + cart2.hashCode());

/*
cart1에 담긴 내용 : [붕어빵 1000 Thu Jun 08 21:58:40 KST 2023, 딸기우유 1500 500]
cart2에 담긴 내용 : [지리산암반수 3000 500]
cart1의 hashcode : 1946988038
cart2의 hashcode : 1990519794
*/

ShoppingCart의 bean scope를prototype으로 설정하자 getBean으로 인스턴스를 꺼내올 때 마다 새로운 인스턴스를 생성하게 된다. 따라서 이번 예제에서는 손님 두 명이 각각 쇼핑 카트를 이용해 상품을 담는 상황이 잘 연출되었다.

 

3. xml 설정

의 예제에서는 모두 Java 빈 객체 설정을 통해 확인해보았다. 만약 XML 파일에<bean> 태그를 이용한다면 다음과 같이 속성을 기재할 수 있다.

<!-- singleton 설정 --> 
<bean id="cart" class="패키지명.ShoppingCart" scope="singleton"/>

<!-- prototype 설정 -->
<bean id="cart" class="패키지명.ShoppingCart" scope="prototype"/>

XML 설정에 대한 별도의 실행 예제는 생략한다.

728x90
반응형
728x90
반응형

[Spring Framework] Spring Boot DI 완벽 정리 | @Resource 활용법

 

[Spring Framework] Spring Boot DI 완벽 정리 | @Resource 활용법

[Spring Framework] Spring Boot DI 핵심 가이드 | @Primary와 @Qualifier 제대로 이해하기 [Spring Framework] Spring Boot DI 핵심 가이드 | @Primary와 @Qualifier 제대로 이해하기[Spring Framework] Spring Framework 의존성 주입(DI)

crushed-taro.tistory.com

1. DI Annotation

1. @Inject

@Inject 어노테이션은 자바에서 제공하는 기본 어노테이션이다. @Autowired 어노테이션과 같이 Type으로 빈을 의존성 주입한다.

당 어노테이션은 사용하기 전 라이브러리 의존성 추가가 필요하므로 Maven Repository에서javax inject을 검색하여 build.gradle.kts파일에 아래와 같은 구문을 추가한다.

dependencies {
	implementation("javax.inject:javax.inject:1")
	...생략
}

 

1. 필드 주입

드로Pokemon 타입의 객체를 의존성 주입 받는 PokemonService 클래스를 선언한다. @Inject 어노테이션은 Type 으로 의존성 주입하므로 3개의 동일한 타입의 빈이 있는 현재 상황에서는 오류가 발생한다. 따라서 @Named어노테이션을 함께 사용해서 빈의 이름을 지정하면 해당 빈을 의존성 주입할 수 있다.

@Service("pokemonServiceInject")
public class PokemonService {

	/* 1. 필드 주입 */
	@Inject
	@Named("pikachu")
	private Pokemon pokemon;

	public void pokemonAttack() {
		pokemon.attack();
	}
}

CharmanderPikachuSquirtlePokemonService 를 빈 스캐닝 할 수 있는 basePackages를 설정하여 스프링 컨테이너를 생성한다.

ApplicationContext context = new AnnotationConfigApplicationContext("project");

PokemonService pokemonService = context.getBean("pokemonServiceInject", PokemonService.class);
		
pokemonService.pokemonAttack();

/*
피카츄 백만볼트⚡
*/

 

2. 생성자 주입

성자로Pokemon 타입의 객체를 의존성 주입 받는 PokemonService클래스를 선언한다.

@Service("pokemonServiceInject")
public class PokemonService {

	private Pokemon pokemon;

	/* 2. 생성자 주입 */
	@Inject
	public PokemonService(@Named("pikachu") Pokemon pokemon) {
		this.pokemon = pokemon;
	}

	public void pokemonAttack() {
		pokemon.attack();
	}
}

/*
피카츄 백만볼트⚡
*/

@Named어노테이션의 경우 메소드 레벨, 파라미터 레벨에서 둘 다 사용 가능하다.

 

3. 세터 주입

터로Pokemon타입의 객체를 의존성 주입 받는PokemonService클래스를 선언한다.

@Service("pokemonServiceInject")
public class PokemonService {

	private Pokemon pokemon;

	/* 3. 세터 주입 */
	@Inject
	public void setPokemon(@Named("pikachu") Pokemon pokemon) {
		this.pokemon = pokemon;
	}

	public void pokemonAttack() {
		pokemon.attack();
	}
}

/*
피카츄 백만볼트⚡
*/

@Inject는 필드 주입생성자 주입세터 주입모두 가능하다.

 

정리

DI는 스프링 프레임워크에서 매우 중요한 개념 중 하나로, 개발자는 객체 간의 의존성을 직접 관리하지 않고 스프링 컨테이너가 객체 간의 의존성을 주입해주는 방식으로 관리할 수 있다.

다양한 DI 어노테이션이 있는데 각각의 특징과 사용 방식이 다르다.

  @Autowried @Resource @Inject
제공 Spring Java Java
지원 방식 필드, 생성자, 세터 필드, 세터 필드, 생성자, 세터
빈 검색 우선 순위 타입 → 이름 이름 → 타입 타입 → 이름
빈 지정 문법 @Autowired
@Qualifier(”name”)
@Resource(name=”name”) @Inject
@Named(”name”)
728x90
반응형

+ Recent posts