[스프링 프레임워크 핵심기술] ApplicationContext와 다양한 빈 설정 방법

Dayeon myeong·2021년 2월 18일
0

스프링 IoC 컨테이너의 역할

  • 빈 인스턴스 생성
  • 의존관계 설정
  • 빈 제공

ApplicationContext

IoC 컨테이너에 있는 ApplicationContext와 BeanFactory(ApplicationContext는 BeanFactory를 상속받는다.) 인터페이스 덕분에 Bean으로 지정한 모든 클래스를 빈으로 등록해주어 다른 클래스에서 의존관계가 필요하다면 이 Bean(스프링 IoC 컨테이너가 관리 하는 객체)으로 등록된 인스턴스들을 전달해주어 의존성 주입(Dependency Injection)이 가능해진다

빈 설정 1 - xml 파일

public class BookRepository {
}
public class BookService {

    BookRepository bookRepository;
    //setter 주입방식
    public void setBookRepository(BookRepository bookRepository) {
        this.bookRepository = bookRepository;
    }
}
public class DemoApplication {
    public static void main(String[] args) {
    ApplicationContext context
            = new ClassPathXmlApplicationContext("application.xml");
    String[] beanDefinitionNames = context.getBeanDefinitionNames();
    System.out.println(Arrays.toString(beanDefinitionNames));

    BookService bookService = (BookService) context.getBean("bookService");
    System.out.println(bookService.bookRepository != null);

    }
}

빈과 해당 빈에 주입할 빈을 설정해준다.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       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">
    <bean id="bookService"
          class="com.inflearnspringframeworkbasic.demo.BookService">
        <property name="bookRepository" ref="bookRepository"/>
    </bean>

    <bean id="bookRepository" class="com.inflearnspringframeworkbasic.demo.BookRepository"/>
</beans>

일일이 빈 등록해야함.번거롭다

그래서 나온게 component scan으로 빈 등록 , 빈 주입시 @Autowired

빈 설정 2 - component-scan

<context:component-scan base-package="..">으로 base-package에 적어둔 package부터 하위까지 모두 스캔하여 Bean을 등록해준다.
@Component 어노테이션(@Component를 확장한 @Service, @Repository,,도 가능)을 사용한 클래스를 빈으로 모두 자동 등록해준다.
이후 빈을 주입받으려면 @Autowired를 사용한다.

@Repository
public class BookRepository {
}

@Service
public class BookService {

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

    <context:component-scan base-package="com.inflearnspringframeworkbasic.demo"/>
</beans>

동일값 출력됨

빈 설정 3 - 자바 설정 파일

@Configuration 가 붙은 클래스를 통해 빈을 모두 등록해준다. 빈을 일일이 등록해야한다.
의존성 주입은 아래의 세가지 방식이 있다.

  • 메소드 이름으로 주입해주는 방법
  • 파라미터로 받아 주입해주는 방법
  • @Autowired를 쓰는 방법

빈 설정 4 - 자바 설정 파일에 ComponentScan

자바 설정파일에 @ComponentScan 어노테이션을 붙여 @Component가 붙은 클래스 혹은 @Compoenent를 확장한 클래스(@Repository,@Service,,)를 모두 빈으로 등록한다.


@Configuration
@ComponentScan(basePackageClasses = DemoApplication.class)
public class ApplicationConfig {

}
@Repository
public class BookRepository {
}

@Service
public class BookService {

    @Autowired
    BookRepository bookRepository;

    public void setBookRepository(BookRepository bookRepository) {
        this.bookRepository = bookRepository;
    }
}

@SpringBootApplication으로 간단하게 사용가능

빈 설정 5 - SpringBootApplication

configuration과 component scan이 다 속해있기 때문에 @SpringBootApplication어노테이션만으로 @Component 어노테이션이 붙은 빈을 모두 등록가능하다.

profile
부족함을 당당히 마주하는 용기

0개의 댓글