: 제어권 역전.
일반적인 제어권 상황과 IoC 상황을 코드로 예를 들어 설명하겠다.
객체 의존성에 대한 일반적인 제어권 Example
class OwnerController{
private OwnerRepository owner = new OwnerRepository();
}
IoC(Inversion of Control) Example
class OwnerController {
private OwnerRepository owner;
public OwnerController(OwnerRepository owner) {
this.owner = owner;
}
}
Spring 의 IoC 컨테이너가 관리하는 자바 객체를 Bean 이라고 한다.
Spring 에서 의존성 주입(DI, Dependency Injection)을 받기 위해서는
이러한 자바 객체를 IoC 컨테이너에 Spring Bean으로 등록해야 가능하다.
Component Scanning Example
@Controller
public class SampleBeanController {
}
직접 등록 Example | SampleBeanConfig.java
@Configuration
public class SampleBeanConfig {
@Bean
public SampleBeanController sampleBeanController(){
return new SampleBeanController();
}
}
Example
@Autowired
private OwnerRepository owners;
@Autowired
private ApplicationContext applicationContext;
@Autowired
private VisitRepository visits;
@Autowired
private PetRepository petRepository;
Example
@RunWith(SpringRunner.class)
@SpringBootTest
public class SampleBeanControllerTest {
@Autowired
ApplicationContext applicationContext;
// ApplicationContext에 SampleBeanController가 Bean으로 등록되어 있는지
// 확인하는 테스트 코드
@Test
public void testDI() {
SampleBeanController bean = applicationContext.getBean(SampleBeanController.class);
assertThat(bean).isNotNull();
}
}
: 필요한 의존성 객체를 어떻게 주입 받을 것인가
Example
@Controller
class OwnerController {
// 의존성 객체를 생성자를 통해서 주입 받는 방식 (Spring Framework 에서 권장하는 방식)
private final OwnerRepository owners;
private final ApplicationContext applicationContext;
private VisitRepository visits;
private final PetRepository petRepository;
public OwnerController(OwnerRepository clinicService,
VisitRepository visits,
ApplicationContext applicationContext,
PetRepository petRepository) {
this.owners = clinicService;
this.visits =
visits;
this.applicationContext = applicationContext;
this.petRepository = petRepository;
}
}
Example
@Autowired
private OwnerRepository owners;
@Autowired
private ApplicationContext applicationContext;
@Autowired
private VisitRepository visits;
@Autowired
private PetRepository petRepository;
Example
private OwnerRepository owners;
private ApplicationContext applicationContext;
private VisitRepository visits;
private PetRepository petRepository;
@Autowired
public void setOwners(OwnerRepository owners) {
this.owners = owners;
}
@Autowired
public void setApplicationContext(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
@Autowired
public void setVisits(VisitRepository visits) {
this.visits = visits;
}
@Autowired
public void setPetRepository(PetRepository petRepository) {
this.petRepository = petRepository;
}