스프링의 기본 컨셉에 대한 정리
말 그대로 생성자를 통해 주입
인스턴스 선언 시에는 final 붙이고, 생성자에서 주입해줌 (생성자에 @Autowired 붙음)
장점: final 때문에 불변성 보장
setter 같은 수정자 통해 주입 (마찬가지로 setter에 @Autowired 붙음)
선택, 변경 가능성이 있는 의존관계에서 사용
인스턴스 선언시 거기에 @Autowired붙임
코드는 간결하지만 외부에서 변경이 불가능하기 때문에 테스트하기 힘들다는 치명적 단점
사용하지마라~!
말 그래도 일반 메서드 주입
잘 안 씀
이론을 이해하기 위해 작성했고, 현재는 컴포넌트 스캔을 더 자주 쓰는 것 같음
public interface SpeakingLanguage {
String introduceSelf();
}
public class French implements SpeakingLanguage {
@Override
public String introduceSelf() {
return "Salut Je parle français";
}
}
public class English implements SpeakingLanguage {
@Override
public String introduceSelf() {
return "Hi I speak English";
}
}
@Configuration
public class LanguageConfig {
@Bean
public SpeakingLanguage speakingLanguage() { return new French(); }
}
public class LanguageTest {
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(LanguageConfig.class);
SpeakingLanguage speakingLanguage = applicationContext.getBean("speakingLanguage", SpeakingLanguage.class);
@Test
public void 현재_설정된_언어(){
System.out.println(speakingLanguage.introduceSelf());
}
}

public interface SpeakingLanguage {
String introduceSelf();
}
@Component
@Primary
public class French implements SpeakingLanguage {
@Override
public String introduceSelf() {
return "Salut Je parle français";
}
}
@Component
public class English implements SpeakingLanguage {
@Override
public String introduceSelf() {
return "Hi I speak English";
}
}
@SpringBootTest
public class LanguageTest {
@Autowired
private SpeakingLanguage speakingLanguage;
@Test
public void 현재_설정된_언어(){
System.out.println(speakingLanguage.introduceSelf());
}
}

DI와 객체지향을 정리하다보니 둘의 장점이 구분하기 힘들다고 느꼈다. 생각해보니 DI는 객체지향의 장점을 더 극대화 시킨 방식이라고 느꼈다. 기본적인 의미에서의 객체지향에서는 해당 클래스가 구체적으로 어떻게 구현되어있는지 몰라도 쓸 수 있었지만, 어떻게 생성하는지는 알아야한다. 하지만 DI를 사용한다면 구체적 구현 뿐만 아니라 생성자의 형태도 몰라도 된다. 라고 느꼈다.
public class NotificationService {
private EmailService emailService = new EmailService(); // 강한 결합
public void sendNotification(String message) {
emailService.sendEmail(message);
}
}
public class NotificationService {
private final EmailService emailService;
@Autowired
public NotificationService(EmailService emailService) {
this.emailService = emailService; // DI를 통해 주입
}
public void sendNotification(String message) {
emailService.sendEmail(message);
}
}
상위코드가 단순히 객체지향만을 생각했을 때고
하위코드가 DI까지 사용했을 때의 코드이다
현재는 생성자에 따로 넘겨줄 인자가 없기 때문에 비슷해 보이지만, 생성자에 넘겨줘야할 정보가 있다고 생각하면 차이점이 좀 더 잘 보일 것이다.
되돌아보니 아는 게 제대로 없다는 생각에서 시작된 바닥부터 다시 공부하기
하면 할 수록 자괴감들지만 언젠가 이게 밑거름이 되길 바라며