public class MainApp { public static void main(String[] args) { // ClassPathXmlApplicationContext를 사용하여 Spring 컨텍스트를 초기화합니다. ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); // 컨텍스트에서 MyService 타입의 빈을 가져옵니다. MyService myService = context.getBean(MyService.class); // myService 객체의 메서드를 호출하여 작업을 수행합니다. myService.performTask(); }}
설명:
ClassPathXmlApplicationContext: XML 설정 파일을 읽어들이기 위해 사용되는 Spring 컨텍스트입니다.
XML 파일에서 <bean> 태그를 사용하여 빈을 정의하고, ref 속성을 통해 의존성을 주입합니다.
@Configurationpublic class AppConfig { @Bean public MyRepository myRepository() { return new MyRepositoryImpl(); } @Bean public MyService myService() { return new MyServiceImpl(myRepository()); }}
public class MainApp { public static void main(String[] args) { // AnnotationConfigApplicationContext를 사용하여 Spring 컨텍스트를 초기화합니다. ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class); // 컨텍스트에서 MyService 타입의 빈을 가져옵니다. MyService myService = context.getBean(MyService.class); // myService 객체의 메서드를 호출하여 작업을 수행합니다. myService.performTask(); }}
설명:
@Configuration: 이 클래스가 Spring 설정 클래스임을 나타냅니다.
@Bean: 이 메서드가 반환하는 객체를 Spring IoC 컨테이너에서 관리하는 빈으로 등록합니다.
AnnotationConfigApplicationContext: 자바 기반 설정 파일을 읽어들이기 위해 사용되는 Spring 컨텍스트입니다.