스프링

[Spring]스프링 개념

easy-6 2024. 11. 20. 17:25

1. 스프링 프레임 워크란?

→ 자바 플랫폼을 위한 오픈소스 애플리케이션 프레임워크

→  엔터프라이즈급 애플리케이션을 개발하기 위한 모든 기능을 종합적으로 제공하는 경량화된 솔루션


자바 개발을 위한 프레임워크로 종속 객체를 생성해주고 ,  조립해주는 도구

1.1 스프링 프레임워크의 특성 

1).경량 컨테이너로 애플리케이션 객체의 생명 주기와 설정을 포함하고 직접 관리한다.
(이때 컨테이너는 서버와 같다고 볼 수 있다)

 

ex) 톰캣 >>> 서버의 종류 중 한 개 
 
2) POJO방식으로 크기와 부하의 측면에서 경량이다.

POJO >> 자바로 생성되는 순수 데이터 

 

// (1) 데이터가 생성되는데 의존이 없이 순수하게 생성이 되는 POJO의 예시
A a = new A(); 
a.method1();
// (2) 의존이 있는 데이터의 예시
class A {
    private B b;

    // 생성자 주입 (Constructor Injection)
    public A(B b) {
        this.b = b;
    }

    public void method() {
        b.someMethod();
    }
}

B b = new B();
A a = new A(b); // B 객체가 외부에서 주입됨
a.method();

 (1)은 메소드를 생성하는데 의존 주입 없이 스스로 생성 가능 

 (2) 는 a의 메소드를 실행하기 위해서  b에게 의존이 필요하기 때문에 POJO가 아님

3) 제어 역행(IoC)을 지원

  객체 생성을 사용자가 하는 내용이 아닌 ioc 컨테이너가 하는것

4) 의존성 주입(DI : Dependency Injection)을 지원
의존성 주입 (DI ): POJO가 아니고 위의 예시 (2) 처럼 어떠한 메소드를 실행하기 위해서 외부에서 다른 객체가 주입이 되어야 하는 기능 
5) 관점지향(AOP) 프로그래밍을 지원
트랜잭션이나 로깅, 보안과 같이 여러 모듈에서 공통적으로 사용하는 기능의 경우 해당 기능을 분리하여 관리할 수 있다.

aop 예시

 

5-1) aopEx02 패키지 내부의 Aop.java

package aopEx02;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

/*
 * 현재 클래스는	여러가지 공통 모듈 (메소드)를 관리하는 클래스

 *  	aop 사용시 공통 관심사 별로 클래스 분류 기능들을 메소드로 관리하게 된다.
 
 * aop 프로그램을 하기 위해선 aspect와 target 전부 ioc 컨테이너가 생성한 객체들 끼리만 적용이 가능하다.
 <aop 용어 정리 > 
 1. aspect : 관심사라는 의미로 같은 관심사별 공통 모듈을 담고 있는 그룹 또는 클래스를 의미한다.
 2. target : aspect를 적용할 클래스 또는 메소드를 의미함 .
 3. advice : 실질적으로 어떤 일을 해야할 지에 대한 것으로 부가 기능을 담을 구현체 
 4. joinpoint : 공통 기능이 적용되어야하는 핵심 기능의 시점 
 5. pointcut : joinpoint의 상세한 스펙을 의미함. 
 
 */
// 컴포넌트이면서 동시에 어스펙트 설정 
@Aspect
@Component
public class Aop {
	// 핵심 로직 실행 전에 호출 될 공통 모듈
	@Before("wihin(패키지명.클래스)")
	public void beforAdvice() {
		System.out.println("핵심 로직 실행 전에 호출되는 공통모듈입니다.");
	}
	@After("within(패키지명.클래스)")
	public void afterAdvice() {
		System.out.println("핵심 로직 실행 후 호출되는 공통 모듈입니다.");
	}
	/*
		2-1 after-throwing : 핵심로직 실행 시 에러발 생 후 
		2-2 after-returning : 핵심로직 정상 종료 후
	 */
	@AfterThrowing("within(패키지명.클래스)")
	public void afterThrowingAdvice() {
		System.out.println("핵심 로직이 에러가 발생하여 종료 되었습니다.");
	}
	
	@AfterReturning("within(패키지명.클래스)")
	public void afterReturningAdvice() {
		System.out.println("핵심로직이 정상 종료 되었습니다.");
	}
	@Around("within(패키지명.클래스)")
//	around는 핵심 로직이 매개변수로 들어와야함
	public Object aroundAdvice(ProceedingJoinPoint joinpoint) throws Throwable {
		System.out.println("핵심로직 실행전");
		try {
			System.out.println("핵심로직 실행전2");
			
			Object obj = joinpoint.proceed(); // 핵심 로직 실행  // 따라서 핵심 로직 위에 실행전 메소드 사용 가능 
			return obj; // return 뒤에는 강제 종료 
		} finally {
			System.out.println("핵심 로직 실행 후 ");
		}
	}
}

 

5-2) applicationcontext.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"
	xmlns:aop="http://www.springframework.org/schema/aop"
	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.2.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd">
<context:component-scan base-package="aopEx02"/>		<!-- component로 선언한 객체를 생성  -->
<aop:aspectj-autoproxy/> 								<!-- aop 어노테이션을 실행함  -->
</beans>

위의 코드를 보고 어떻게 작동하는지 알 수 있음