[JAVA] Annotation(애너테이션) vs Method(메서드)
0. 먼저 읽어보기
[Java] @, Annotation(애너테이션) 완벽 가이드
애너테이션(Annotation)은 Java 코드에 추가적인 정보를 제공하는 메타데이터이다. • 컴파일러, 런타임 환경, 프레임워크(Spring 등)가 특정 기능을 수행할 때 활용된다. • 주석(Comment)과 달리 실제
jyhan0625.tistory.com
애너테이션 대신 그냥 메서드로 객체를 생성하고 관리할 수도 있다.
하지만 애너테이션을 사용하는 것이 훨씬 편리하고 유지보수에 유리하다.
1. 애너테이션 없이 직접 객체 생성하는 경우
public class MyService {
private MyRepository repository;
// 생성자를 통해 의존성 주입
public MyService(MyRepository repository) {
this.repository = repository;
}
public void doSomething() {
System.out.println("Service is working...");
}
}
public class App {
public static void main(String[] args) {
// 수동으로 객체를 생성하고 연결해야 함
MyRepository myRepository = new MyRepository();
MyService myService = new MyService(myRepository);
myService.doSomething();
}
}
❌ 문제점
1) 객체 생성 및 관리가 번거롭다.
• MyRepository → MyService 순서대로 직접 생성해야 함
• 프로젝트가 커질수록 수작업이 많아짐
2) 의존성 관리가 어렵다.
• MyService가 MyRepository를 직접 받아야 하므로 결합도가 높아짐
• 변경이 발생하면 여러 곳을 수정해야 함
2. 애너테이션을 사용하면?
import org.springframework.stereotype.Component;
import org.springframework.beans.factory.annotation.Autowired;
@Component // Spring이 자동으로 빈 등록
public class MyService {
private final MyRepository repository;
@Autowired
public MyService(MyRepository repository) {
this.repository = repository;
}
public void doSomething() {
System.out.println("Service is working...");
}
}
@Component // Spring이 자동으로 빈 등록
public class MyRepository {
public MyRepository() {
System.out.println("Repository Created!");
}
}
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class App {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
// 직접 new 하지 않고 Spring 컨테이너에서 가져옴
MyService myService = context.getBean(MyService.class);
myService.doSomething();
}
}
✅ 장점
1) 객체 생성 및 관리 자동화
• @Component가 붙은 클래스는 Spring이 알아서 빈으로 등록
• @Autowired로 필요한 객체를 자동으로 주입받음
• 개발자는 객체 생성 로직을 직접 신경 쓸 필요 없음
2) 결합도가 낮아짐
• MyService는 MyRepository를 직접 생성하지 않음
• 필요한 객체를 Spring이 알아서 주입해주므로 유지보수가 쉬워짐
3) 코드가 간결해짐
• new 키워드를 직접 사용하지 않아도 됨
• ApplicationContext에서 빈을 관리해주므로 전체 코드가 깔끔해짐
3. 결론: 애너테이션이 없으면?
• 가능은 하지만 객체 생성과 의존성 관리가 번거롭고 유지보수가 어려워진다.
• 애너테이션을 사용하면 Spring이 알아서 객체를 관리하고, 결합도가 낮아져 유지보수가 쉬워진다.
💡 즉, 애너테이션(@Component, @Autowired 등)은 객체 관리 및 의존성 주입을 간편하게 해주는 도구이다! 🚀