import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component // 스프링이 관리하는 Bean
class B {
public void doSomething() {
System.out.println("B가 일을 합니다!");
}
}
@Component // 스프링이 관리하는 Bean
class A {
private final B b;
// 생성자 주입 (권장 방식)
@Autowired // 스프링이 관리하는 Bean객체를 자동으로 주입
public A(B b) {
this.b = b; // 스프링 컨테이너가 B 객체를 대신 넣어줌
}
public void action() {
b.doSomething();
}
}
-----------------------
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Bean
public CommandLineRunner run(A a) { // Bean 등록
return args -> {
a.action(); // "B가 일을 합니다!"
};
}
}
@Component - 이 클래스를 스프링 컨테이너가 관리하는 Bean으로 등록
스프링이 실행될때 @Component가 붙은 클래스를 찾아서 객체를 자동으로 생성한뒤 보관. new B()를 안해도 스프링이 대신 B 객체를 만들어서 관리
@Component → 클래스(A, B)를 스프링이 자동으로 객체 생성 & 관리.
@Autowired → A가 필요로 하는 B 객체를 컨테이너에서 꺼내서 자동으로 넣어줌.
@Bean → 스프링 실행 시 CommandLineRunner라는 Bean도 만들고, 여기서 a.action() 실행.