Spring 숙련
@Configuration @ComponentScan public class AppConfig { @Bean Car car() { return new Car(); } @Bean @Scope("prototype") // default - @Scope("singleton") Engine engine() { return new Engine(); } @Bean Door door() { return new Door(); } }
@Component class Car { Engine engine; Door door; @Override public String toString() { return "Car{" + "engine=" + engine + ", door=" + door + '}'; } } @Component class Engine { } @Component class Door { } public class Main { public static void main(String[] args) { // AC 생성 - AC의 설정파일은 AppConfig.class 자바설정 ApplicationContext ac = new AnnotationConfigApplicationContext(AppConfig.class); // Car car = (Car)ac.getBean("car"); // byName Car car = ac.getBean("car", Car.class); // 형변환 대신 경로 지정, 위와 동일 코드 // Bean @Scope("prototype") 붙어있어 여러개 생성 가능 Engine engine = ac.getBean(Engine.class); // byType, 형변환 불필요 Engine engine2 = ac.getBean(Engine.class); // byType, 형변환 불필요 Engine engine3 = ac.getBean(Engine.class); // byType, 형변환 불필요 System.out.println("car = " + car); System.out.println("engine = " + engine); System.out.println("engine2 = " + engine2); System.out.println("engine3 = " + engine3); System.out.println("ac.getBeanDefinitionCount() = " + ac.getBeanDefinitionCount()); System.out.println("ac.getBeanDefinitionNames() = " + Arrays.toString(ac.getBeanDefinitionNames())); // System.out.println("ac.containsBeanDefinition(\"engine\") = " + ac.containsBeanDefinition("engine")); // System.out.println("ac.isSingleton(\"car\") = " + ac.isSingleton("car")); // System.out.println("ac.isPrototype(\"engine\") = " + ac.isPrototype("engine")); } }