[ Spring ] @Autowired Annotation
2024. 2. 14. 19:18ㆍ· BACK-END/└ Spring Boot
환경 : Spring Tool Suite4
@Autowired 어노테이션
- 스프링의 의존성 주입(Dependency Injection, DI)을 위해 사용
- 주로 생성자, 필드, 메서드, 설정 메서드(Setter) 등에 적용 됨.
- 스프링 컨테이너가 해당 타입의 Bean을 찾아 자동으로 주입하도록 지정
- 코드가 간결해지므로 가독성이 향상되며 동시에 편의성도 좋아짐
- 의존성 주입의 유연성으로 인해 컴포넌트 간의 느슨한 결합을 유지할 수 있음
- @Autowired를 사용하는 경우에는 해당 빈이 존재하지 않으면 예외 발생 가능. 이를 방지하기 위해 @Autowired(required = false)와 같이 설정
- @Autowired를 통한 주입보다 생성자 주입을 선호하는 경우도 있음. 생성자 주입은 빈을 더욱 명확하게 표현할 수 있고, 변경 불가능한(final) 필드를 사용할 수 있습니다.
[ @Autowired 를 사용하지 않은 경우 ]
- 설정해줘야 하는 것들이 상대적으로 많다.
- MyService.java -
public class MyService {
private MyRepository myRepository;
public MyService(MyRepository myRepository) {
this.myRepository = myRepository;
}
// 이하 나머지 코드
}
- MyRepository.java -
public class MyRepository {
// 이하 나머지 코드
}
- spring-config.xml(XML 설정 파일) -
<!-- MyService 빈 설정 -->
<bean id="myRepository" class="com.example.MyRepository" />
<bean id="myService" class="com.example.MyService">
<constructor-arg ref="myRepository" />
</bean>
(+) <bean> 요소는 각각 'MyRepository'와 'MyService'에 대한 빈을 정의
(+) 'myService' 빈은 생성자를 통해 'myRepository' 빈을 주입받도록 설정
- Java 코드에서 XML 설정 파일 로드 -
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyApp {
public static void main(String[] args) {
// XML 설정 파일을 로드하여 ApplicationContext 생성
ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
// MyService 빈을 가져와서 사용
MyService myService = context.getBean("myService", MyService.class);
// 이하 나머지 코드
}
}
(+) ClassPathXmlApplicationContext를 사용하여 XML 설정 파일을 로드하고,
getBean 메서드를 통해 myService 빈을 가져 옴
[ @Autowired 를 사용하는 경우 ]
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class MyService {
private MyRepository myRepository;
@Autowired
public MyService(MyRepository myRepository) {
this.myRepository = myRepository;
}
// 이하 나머지 코드
}
(+) '@Autowired' 어노테이션을 작성해줌으로써 알아서 의존성 주입을 받게 됨
개인 공부 기록용입니다:)
예시 코드는 Chat GPT 활용
728x90
'· BACK-END > └ Spring Boot' 카테고리의 다른 글
[ Spring ] @RequestParam Annotation (0) | 2024.02.17 |
---|---|
[ Spring ] @ModelAttribute Annotation (0) | 2024.02.15 |
[ Spring ] @Controller와 @RestController의 차이 (0) | 2024.02.12 |
[ Spring ] @Repository / @Service / @Controller (0) | 2024.02.11 |
[ Database / Spring ] 데이터베이스 연동하기 및 파라미터를 통해 데이터 삽입해보기 (0) | 2024.02.09 |