memo6759 님의 블로그
2025-11-18(Spring) 본문
생성자 주입
1. Constructor Injection
- 주로 사용하는 방식
- 생성자를 통해 Ioc 컨테이너가 의존모듈을 주입해주므로 생성자를 미리 정의
여기서 의존성 주입이란?
Spring Boot에서 의존성 주입은 객체 간의 의존 관계를 자동으로 설정해주는 중요한 개념
이를 통해 코드의 결합도를 낮추고, 유지보수성을 높임.
의존성 주입을 통해 클래스 간의 결합도를 낮출 수 있다. 결합도가 낮아지면, 한 클래스의 변경이 다른 클래스에 미치는 영향을 줄일 수 있다. 이는 코드 강 결합 <----의존성 주입----->약결합 의 유지보수성과 확장성을 높이는데 중요한 역할은 한다.
예를 들어, 클래스 A가 클래스 B에 직접 의존하는 경우 B의 변경사항은 A에 직접적인 영향을 미치게 된다. 하지만 의존성 주입을 하면 A는 B의 구체적인 구현이 아니라 인터페이스나 추상 클래스에 의존하게 되어, B의 구현 변경이 A에 미치는 영향을 최소화 가능
강결합
public class B {
public void doSomething() {
System.out.println("Doing something in B");
}
}
public class A {
private B b;
public A() {
this.b = new B(); // 강한 결합
}
public void performAction() {
b.doSomething();
}
public static void main(String[] args) {
A a = new A();
a.performAction();
}
}
약 결합 예시 코드
// 인터페이스 정의
public interface Service {
void doSomething();
}
// 인터페이스 구현체 1
public class ServiceImpl implements Service {
@Override
public void doSomething() {
System.out.println("Doing something in ServiceImpl");
}
}
// 인터페이스 구현체 2
public class AnotherServiceImpl implements Service {
@Override
public void doSomething() {
System.out.println("Doing something in AnotherServiceImpl");
}
}
// 의존성 주입을 통해 느슨한 결합 구현
public class A {
private final Service service;
// 생성자 주입
public A(Service service) {
this.service = service;
}
public void performAction() {
service.doSomething();
}
public static void main(String[] args) {
// ServiceImpl 주입
Service service1 = new ServiceImpl();
A a1 = new A(service1);
a1.performAction();
// AnotherServiceImpl 주입
Service service2 = new AnotherServiceImpl();
A a2 = new A(service2);
a2.performAction();
}
}
느슨한 결합을 구현하기 위해 인터페이스를 사용하고, 의존성 주입을 통해 클래스 간의 결합도 낮춤
의존성 주입 방법
1. 필드 주입
클래스 멤버 변수에 직접 주입하는 방법
package com.iot.springdi.annotation.basic.exam2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
//비지니스로직
@Service("insa")
public class InsaImpl implements Insa {
//필드의 자동 주입
@Autowired
MemberDAO dao;
public InsaImpl(MemberDAO dao) {
this.dao = dao;
}
@Override
public void addUser(MemberDTO user) {
dao.add(user);
}
@Override
public MemberDTO getUser(String id) {
dao.getUser("id");
return null;
}
}

2. 생성자 주입
생성자를 통해 의존성을 주입하는 방법, 최근에는 더 권장되고 있음(@RequiredConstructor로 해도 됨)
@Service
public class MyService {
private final MyRepository myRepository;
@Autowired
public MyService(MyRepository myRepository) {
this.myRepository = myRepository;
}
}
3. 세터 주입
세터 메서드를 통해 의존성을 주입하는 방법
@Service
public class MyService {
private final MyRepository myRepository;
@Autowired
public MyService(MyRepository myRepository) {
this.myRepository = myRepository;
}
}
@Autowired
Spring 에서 @Autowired 어노테이션은 의존성 주입을 간편하게 해주는 기능이다.
@Autowired의 원리 스프링 IoC컨테이너는 애플리케이션의 빈(bean)을 관리한다. 빈은 스프링 컨테이너에 의해 생성되고 관리되는 객체 빈 정의는 XML파일, 자바 설정 클래스 (@Configuration, @Bean), 또는 컴포넌트 스캔(@Component, @Service, @Repository, @Controller) 등을 통해 이루어진다.
















'HDC 학습일지' 카테고리의 다른 글
| 2025-11-21(JPA 연관관계, Spring Data JPA) (1) | 2025.11.23 |
|---|---|
| 2025-11-20(JPA) (0) | 2025.11.20 |
| 2025-11-17(Spring) (1) | 2025.11.17 |
| 2025-11-14(서블릿, jsp 구조 파악, 스프링) (0) | 2025.11.17 |
| 2025-11-13(백엔드 - Servlet) (0) | 2025.11.13 |