[Spring] 스프링이란?



  • Category : Spring
  • Tag : Spring


스프링이란?

자바 엔터프라이즈 애플리케이션 개발에 사용되는 애플리케이션 프레임워크.

애플리케이션 프레임워크

개발을 빠르고 효율적으로 할 수 있도록 애플리케이션의 바탕이 되는 틀공통 프로그래밍 모델, 기술 API등을 제공 해 준다.



1. 애플리케이션의 기본 틀 - 스프링 컨테이너

  • Spring은 Spring Containner또는 Application Context(XML파일)라고 불리는 Spring runtime Engine을 제공
    • Spring Containner : IoC와 DI를 구현하는 역할



2. 공통 프로그래밍 모델

  • IoC/DI
    • 오프젝트의 생명주기와 의존관계에 대한 프로그래밍 모델
    • IoC(Inversion of Control) : 객체의 생성과 관리를 프레임워크에 위임하는 것
    • DI(Dependency Injection) : IoC의 구현 방법 중 하나로, 객체가 필요로 하는 의존성을 외부에서 주입하는 것
    • 예시코드
      • 기존방식 - instance를 내부에서 직접 생성
        public class MyApplication {
            public void doSomething() {
                ApplicationContext context = new ApplicationContext();
                MyBean myBean = context.getBean("myBean", MyBean.class);
            }
        }
      
      1. 클래스 정의

         @Component
         public class MyBean {
         // ...
         }
        
      2. xml(IoC 컨테이너)에 bean 등록

         <?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="myBean" class="com.example.MyBean" />
        
         </beans>
        
      3. 사용하고자 하는 클래스에서 주입

         public class MyApplication {
             public void doSomething() {
        
                 ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
                 MyBean myBean = context.getBean("myBean", MyBean.class);
             }
         }
        
  • 서비스 추상화
    • 환경이나 서버, 특정 기술에 종속되지 않고 이식성이 뛰어나며 유연한 애플리케이션을 만들 수 있음
    • 서비스 계층의 구현을 담당하는 클래스를 인터페이스와 구현체로 분리
    • 비즈니스 로직의 변경이나 유지보수를 용이
        1. 서비스 인터페이스 : 비즈니스 로직을 추상화한 메서드를 선언한 인터페이스
             public interface UserService {
                 User getUserById(Long id);
                 void saveUser(User user);
             }
          
        1. 서비스 구현체 : 서비스 인터페이스의 메서드를 구현한 클래스
             @Service
             public class UserServiceImpl implements UserService {
          
                 private final UserRepository userRepository;
          
                 public UserServiceImpl(UserRepository userRepository) {
                     this.userRepository = userRepository;
                 }
          
                 @Override
                 public User getUserById(Long id) {
                     return userRepository.findById(id).orElse(null);
                 }
          
                 @Override
                 public void saveUser(User user) {
                     userRepository.save(user);
                 }
             }
          
        1. 서비스 계층: 서비스 인터페이스와 구현체를 모두 포함한 계층으로, 비즈니스 로직을 담당하는 핵심 계층
             @RestController
             @RequestMapping("/users")
             public class UserController {
          
                 private final UserService userService;
          
                 public UserController(UserService userService) {
                     this.userService = userService;
                 }
          
                 @GetMapping("/{id}")
                 public User getUserById(@PathVariable Long id) {
                     return userService.getUserById(id);
                 }
          
                 @PostMapping
                 public void saveUser(@RequestBody User user) {
                     userService.saveUser(user);
                 }
             }
          
  • AOP(Aspect-Oriented Programming)
    • 애플리케이션 코드에 산재하여 나타나는 부가적인 기능을 독립적으로 모듈화하는 프로그래밍 모델
    • AOP는 로깅, 보안, 트랜잭션 처리 등과 같은 공통적인 기능을 모듈화하여 개발하며, 이를 통해 코드의 재사용성과 유지보수성을 향상시킬 수 있음
    • 관심사의 분리(Concern Separation)를 통해 애플리케이션의 로직과 부가적인 기능을 분리하는 것을 목적
    • ‘부가적인 기능’을 공통으로 묶어 공통적인 기능으로 모듈화
    • 예시코드
      1. Aspect 클래스 작성
         @Component
         @Aspect
         public class LoggingAspect {
             // com.example.service 패키지 내에 있는 모든 MEthod를 대상
             @Before("execution(public * com.example.service.*.*(..))")
             public void logBefore(JoinPoint joinPoint) {
                 System.out.println("Logging before method: " + joinPoint.getSignature().getName());
             }
        
             // com.example.service 패키지 내에 있는 모든 MEthod를 대상
             @AfterReturning(pointcut = "execution(public * com.example.service.*.*(..))", returning = "result")
             public void logAfter(JoinPoint joinPoint, Object result) {
                 System.out.println("Logging after method: " + joinPoint.getSignature().getName());
             }
         }
        
      2. XML 파일에 AOP 설정 추가
         <aop:aspectj-autoproxy />
        
         <bean id="loggingAspect" class="com.example.aspect.LoggingAspect" />
        
         <aop:config>
             <aop:aspect id="myAspect" ref="loggingAspect">
                 <aop:before pointcut="execution(public * com.example.service.*.*(..))" method="logBefore" />
                 <aop:after-returning pointcut="execution(public * com.example.service.*.*(..))" method="logAfter" returning="result" />
             </aop:aspect>
         </aop:config>
        
      3. 핵심 로직 클래스 작성
         @Service
         public class UserService {
        
             public void addUser(String name) {
                 System.out.println("Adding user: " + name);
             }
        
             public void deleteUser(int id) {
                 System.out.println("Deleting user with ID: " + id);
             }
         }
        



3. 기술 API

스프링은 엔터프라이즈 애플리케이션을 개발의 다양한 영역에 바로 활용할 수 있는 방대한 양의 기술 API제공


Share this post