상세 컨텐츠

본문 제목

[Spring] @Autowired와 어노테이션에 관해서

JAVA\Spring

by 박집실 2023. 2. 19. 23:45

본문

@Autowired (자동완성주입)

@Autowired 어노테이션은 특정  필드 혹은 수정자 메소드 혹은 생성자에 선언되어있으면 스프링에 자바빈으로 등록되어있는 빈들 중에 같은 타입의 빈을 찾아서 자동으로 할당 및 주입해준다.

 

@Autowired (자동완성주입) 를 쓰기 위한 XML 설정

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">


    <context:annotation-config/>
    <context:component-scan base-package="practice.SpringPRT"></context:component-scan>

    <bean id="dataSource" class="org.springframework.jdbc.datasource.SimpleDriverDataSource">
        <property name="driverClass" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost/testdb?characterEncoding=UTF-8"/>
        <property name="username" value="root"/>
        <property name="password" value="0000"/>
    </bean>
    <!-- <bean id="autoWiredtest" class="practice.SpringPRT.AutoWiredtest"/> 방법으로 빈을 직접 등록하여 사용하여도 작동함, -->
</beans>

 

위에 같이 XML를 설정해주면된다. 특히나 스키마에는 xmlns:context="http://www.springframework.org/schema/context" 를 올바르게 추가해주고 필드 부분에는  

 <context:annotation-config/>    

 <context:component-scan base-package="practice.SpringPRT"></context:component-scan>

를 올바르게 설정해야지만 코드 상에서 어노테이션을 인식하고 사용할 수 있다. 또한 맨 하단의 코드는 설정된 패키지 내의 @autowired를 인식 후 해당하는 객체를 자동으로 주입해주는 세팅이다.

 

또한 이 세팅 후에 @Component나 이를 상속한 @Service @Repository  등 해당 어노테이션을 활용해서 빈으로 등록이 가능하니 굳이 주석처리 되어 있는 곳과 같이 XML 파일에서 직접 세팅해줄 필요가 없다. 

 

[Spring] @Component와 그 자식들에 대해 알아보자 (tistory.com)

 

- 생성자 일 경우

@Autowired
AutoWiredtest(DataSource dataSource) {
    this.dataSource = dataSource;
}

 

다음과 같이 선언해주면 된다. 생성자일 경우에는 @Autowired가 있는 생성자의 파라미터로 DI되는 객체는 스프링 빈 상태여야 한다. 만약 해당 객체가 스프링 빈 상태가 아니라면 해당 객체의 클래스 위에 @Component 혹은 @Repository 어노테이션를 달아주기만 하면 된다. 

 

- 수정자 메서드 일 경우

@Autowired
public void setDataSource(DataSource dataSource) {
    this.dataSource = dataSource;
}

 

다음과 같이 선언해주면 된다. 생성자와는 달리 @Autowired(required = false) 옵션을 통해서 DI 받는 객체가 꼭 스프링 빈이지 않아도 된다.

 

- 필드에 선언하는 경우

@Autowired
static DataSource dataSource;

가장 간단하고 쉬운 형태이지만 의존관계가 한 눈에 보이지 않아서 추천되지 않는 형태이다. 마찬가지로 생성자와는 다르게 @Autowired(required = false) 옵션을 통해서 DI 받는 객체가 꼭 스프링 빈이지 않아도 된다.

 

 

각 방식의 장단점을 참고하기 위해서 해당 링크를 보자!

[Spring] @Autowired란 무엇인가? :: Gyun's 개발일지 (tistory.com)

 

[Spring] @Autowired란 무엇인가?

저번 글에서 IoC 컨테이너와 빈(Bean)등록에 대해서 정리해보았다. 다시 정리하자면 의존성 주입과 빈 등록은 다른 것인데 일단 IoC 컨테이너에 빈으로 등록이 되어야 의존성 주입을 할 수 있다. 저

devlog-wjdrbs96.tistory.com

 

 

 

- 해당하는 bean이 여러 개인 경우 이를 제어하는 방법

 

1. @Primary

 

추후 추가

 

2. @Qulifier

 

추후 추가

 

3. 해당 타입의 bean 모두 주입

 

추후 추가

 

 

 

[스프링 핵심기술] - @Autowired (tistory.com)

 

[스프링 핵심기술] - @Autowired

백기선님의 스프링 프레임워크 핵심 기술이라는 강좌를 들으며 공부한 내용을 정리한 글입니다. 오늘은 @Autowired Annotation의 사용 방법, 동작 원리까지 알아본다. 1. @Autowired란? @Autowired는 의존성

jjingho.tistory.com

 

 

 

 

 

 

 

관련글 더보기