@Controller
public class MainController {
@Autowired
TestService testService;
@GetMapping("test")
public String main (Model model) {
model.addAttribute("data", testService.find());
return "test";
}
}
@Service
public class TestService {
@Autowired
TestRepository testRepository;
public String find() {
String data = testRepository.find();
return data;
}
}
@Repository
public class TestRepository {
public String find() {
return "TEST";
}
}
@Controller
, @Service
, @Repository
어노테이션을 통해 스프링 빈으로 등록된다.@Autowired
를 사용하면 IoC 컨테이너가 해당 객체를 찾아서 자동으로 주입해준다.Controller > Service > Repository > Service > Controller
흐름이 작동하게 된다.@Autowired
어노테이션 생략이 가능하다.@Component
public class Car {
private final Engine engine;
@Autowired
public Car(Engine engine) {
this.engine = engine;
}
}
@Autowired
어노테이션을 사용하는 방법이다.@Component
public class Car {
@Autowired
private final Engine engine;
}
@Component
public class Car {
private final Engine engine;
@Autowired
public void setEngine(Engine engine) {
this.engine = engine;
}
}
2023/11/06 작성
2023/11/14 내용 수정 및 예시 추가