IoC 적용 해보자

리팩토링 벨로그·2022년 9월 29일
0

강의자료에 있는 코드를 다운 받고 압축을 푼 뒤, basic starter 파일인 applicationContext.xml 파일을 copy해준다.

applicationContext.xml 파일 원본

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd"><!-- Define your beans here -->
    
</beans>


1. Configuring Spring Beans

-configuration 파일 수정

그러고 bean에다 id와 fully qualified class name을 적어준다.

<!-- Define your beans here -->
    
    <bean id="myCoach" // the id likes allias)id는 별명(별칭)과 같은 것.
        class="com.luv2code.springdemo.TrackCoach">
    </bean>     
    
</beans>


2. HelloSpringApp이라는 클래스를 새로 만들어보자. 해당 클래스에 main 함수도 넣어주자.

spring configuration file을 로드하기 위해서 다음과 같은 코드를 썼다.

// load the spring configuration file
        ClassPathXmlApplicationContext context = 
                new ClassPathXmlApplicationContext("applicationContex.xml");
        //class path XML Application context 이용



3. Retrieve bean from Spring container

// retrieve bean from spring container
        Coach theCoach = context.getBean("myCoach", Coach.class);
        //bean id와 interface가 getBean에 들어가

// call methods on the bean
        System.out.println(theCoach.getDailyWorkout());


그러고 다음과 같은 코드를 써서 context를 닫아준다.

// close the context
        context.close();

Run As JavaApplication을 눌러주면

이런 식으로 로그가 떠야 되는데 왜 내 것은 이렇게 밖에 안될까?

로그가 안 뜬다. 이유는? 버전 차이 때문

configuration file을 기반으로 App이 configurable해짐 (여기서 App은 MyApp)

configuration, bean과 관련 글 읽어보기
https://jaeano.tistory.com/76
https://castleone.tistory.com/2

이클립스 사용법-
최근 했던 프로젝트에서 부를려면 어떻게 해야 될까?
Desktop/JavaStudy/Springdemo에 /src 등 스프링에 필요한게 있다면 열어야 할 workspace는 JavaStudy에서 열어준다.

궁금한 거-자바 클래스가 여러 개 (ex-src에 .java 파일이 여러 개다.)일 때, main 함수는 몇 개여야 하나?

profile
글 다시 씁니다.

0개의 댓글