Spring 핵심 개념 정리 (POJO, IoC, DI, AOP, PSA)

박진서·2025년 5월 28일
0

Spring

목록 보기
16/17
  1. POJO (Plain Old Java Object)
    개념:
    프레임워크나 환경에 종속되지 않는 순수한 자바 객체. 특정 인터페이스나 상속이 필요 없음.

예시 코드:

public class GreetingService {
    public String greet(String name) {
        return "Hello, " + name;
    }
}
  1. IoC (Inversion of Control)
    개념:
    객체 생성과 의존성 관리를 개발자가 아닌 Spring Container가 대신함.
    즉, 제어의 주도권이 개발자 → 스프링으로 역전(Inversion) 됨.

  2. DI (Dependency Injection)
    개념:
    IoC의 구현 방법 중 하나. 필요한 객체를 직접 생성하지 않고 외부에서 주입받는 방식.

예시 코드:

public interface GreetingService {
    String greet(String name);
}

@Component
public class GreetingServiceImpl implements GreetingService {
    public String greet(String name) {
        return "Hello, " + name;
    }
}

@Component
public class MyApp {
    private final GreetingService greetingService;

    // 생성자 주입 방식 (권장)
    @Autowired
    public MyApp(GreetingService greetingService) {
        this.greetingService = greetingService;
    }

    public void run() {
        System.out.println(greetingService.greet("Spring"));
    }
}

Spring Boot 실행 예시:

@SpringBootApplication
public class App {
    public static void main(String[] args) {
        ApplicationContext context = SpringApplication.run(App.class, args);
        MyApp app = context.getBean(MyApp.class);
        app.run();
    }
}
  1. AOP (Aspect-Oriented Programming)
    개념:
    공통 관심사(로깅, 트랜잭션, 보안 등)를 핵심 로직과 분리하여 구성.

예시 코드:

@Aspect
@Component
public class LoggingAspect {

    @Before("execution(* com.example.service.*.*(..))")
    public void logBefore(JoinPoint joinPoint) {
        System.out.println("메서드 호출 전: " + joinPoint.getSignature().getName());
    }

    @After("execution(* com.example.service.*.*(..))")
    public void logAfter(JoinPoint joinPoint) {
        System.out.println("메서드 호출 후: " + joinPoint.getSignature().getName());
    }
}
  1. PSA (Portable Service Abstraction)
    개념:
    Spring이 다양한 기술(JDBC, JMS, JPA 등)에 대한 추상화 계층을 제공하여 구현체가 달라도 코드 수정 최소화.

예시 코드 (JDBC PSA):

@Repository
public class UserRepository {

    private final JdbcTemplate jdbcTemplate;

    @Autowired
    public UserRepository(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    public List<User> findAll() {
        return jdbcTemplate.query("SELECT * FROM users",
                (rs, rowNum) -> new User(rs.getLong("id"), rs.getString("name")));
    }
}
profile
백엔드 개발자

0개의 댓글