728x90
반응형
DI 설정을 java config로 설정해보기
xml로 설정하면 에러 찾기 여간 까다롭지만 다음과 같이 설정하면
어느 지점에서 에러가 발생하였는지 조금 더 쉽게 찾을 수 있다
Java config를 이용한 설정을 위한 어노테이션
@Configuration
- 스프링 설정 클래스를 선언하는 어노테이션
- java config 클래스를 읽어들여 IoC와 DI를 적용.
@Bean
- bean을 정의하는 어노테이션
- @Bean이 붙은 메소드를 자동 실행하여 그 결과로 반환된 객체들은 기본적으로 싱글턴으로 관리
- 아래의 4 종류의 어노테이션이 붙어 있지 않은 객체는 @Bean으로 직접 생성하여 사용
@ComponentScan
- @Controller, @Service, @Repository, @Component 어노테이션이 붙은 클래스를 찾아 컨테이너에 등록
- 위의 어노테이션이 붙어 있는 객체을 읽어들여 DI를 주입
@Component
- 컴포넌트 스캔의 대상이 되는 애노테이션 중 하나로써 주로 유틸, 기타 지원 클래스에 붙이는 어노테이션
@Autowired
- 주입 대상이되는 bean을 컨테이너에 찾아 주입하는 어노테이션
- 이 어노테이션을 사용하면, setter, getter 메소드를 직접 선언하지 않아도 됨
- 필드, 생성자, setter에 사용할 수 있음
@Configuration , @Bean
ApplicationConfig.java
경로 /src/main/java/ kr.or.connect.diexam01
package kr.or.connect.diexam01;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
// 어노테이션 @
// jdk 5부터 가능
// 사전적 의미는 주석. 그러나 자바에선 특수한 의미를 부여하는 역할
// 컴파일 또는 런타임 시에 해석될 수 있음
// config 파일임을 알려주는 어노테이션
// 이 클래스가 spring 설정 클래스 임을 알려줌
// AnnotationConfig나 ApplicationContext는 나중에
// 이런 자바 config 클래스를 읽어서 IoC와 DI를 적용
@Configuration
public class ApplicationConfig {
// Bean으로 등록된 메소드를 자동 실행하여 객체를 반환해 싱글턴으로 관리
@Bean
public Car car(Engine e) {
Car c = new Car();
c.setEngine(e);
return c;
}
@Bean
public Engine engine() {
return new Engine();
}
}
ApplicationContextExam03.java
경로 /src/main/java/ kr.or.connect.diexam01
파라미터로 class타입 가능 (Car car = ac.getBean(Car.class);)
package kr.or.connect.diexam01;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class ApplicationContextExam03 {
public static void main(String[] args) {
// classpath xml 이 아닌 AnnotationConfigApplicationContext로
// config파일을 정해줌
ApplicationContext ac = new AnnotationConfigApplicationContext(ApplicationConfig.class);
// 자동으로 Bean 객체가 메모리에 다 올라와 있음
Car car = (Car) ac.getBean("car"); // car라고 등록된 메소드를 실행하여 객체 생성
// Car car = (Car) ac.getBean(Car.class); // 클래스 타입을 넣어주는 방법
car.run();
}
}
@ComponentScan , @Component
@Autowired
ApplicationConfig2.java
@ComponentScan으로 Car 클래스와 Engine 클래스를 읽기 위해
두 클래스의 상단에 이것이 컴포넌트라는 표시를 해야한다.
import org.springframework.stereotype.Component;
@Component
public class Engine {
package kr.or.connect.diexam01;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration // config 파일 임을 알려줌
@ComponentScan("kr.or.connect.diexam01") // 스캔할 페키지 명을 꼭 적어야 함
// 알아서 파일을 읽은 뒤 어노테이션 붙을 것들을 등록해줌
// 여기서 읽은 어노테이션은 컨트롤러, 서비스, 리포지토리, 컴포넌트 등이 있음
// 그런 클래스를 찾아서 다 bean으로 등록시켜줌
public class ApplicationConfig2 {
}
setter 메소드도 굳이 쓸 필요 없이 @Autowired 사용하면 된다
@Component
public class Car {
@Autowired
// setter 메소드를 없애고 autowired 어노테이션을 붙임
// 의미는 Engine 타입의 객체가 생성된 게 있으면
// 알아서 v8에 주입하라는 의미 -> setter 필요 없음
private Engine v8;
// public void setEngine(Engine e) {
// this.v8 = e;
// }
ApplicationContextExam04.java
package kr.or.connect.diexam01;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class ApplicationContextExam04 {
public static void main(String[] args) {
// ApplicationConfig -> ApplicationConfig2로 수정
ApplicationContext ac = new AnnotationConfigApplicationContext(ApplicationConfig2.class);
Car car = (Car) ac.getBean("car");
car.run();
}
}
728x90
반응형
'Web > Java+Spring' 카테고리의 다른 글
Spring JDBC - DTO/DAO (0) | 2021.06.02 |
---|---|
Spring JDBC (0) | 2021.06.02 |
Spring IoC/DI 컨테이너 (0) | 2021.06.01 |
Spring Framework (0) | 2021.05.31 |
Web API 실습 (0) | 2021.05.14 |