상세 컨텐츠

본문 제목

ch 23,24 Inversion of Control 코드 쓰기 복습

Spring/Spring&Hibernate 강의

by 빙하둘리 2022. 11. 6. 22:54

본문

728x90

ch19 BaseballCoach.java 클래스 참고

<BaseballCoach.java 클래스 참고>

```java

package com.luv2code.springdemo;

public class BaseballCoach {
public String getDailyWorkout() {
return "Spend 30 minutes on batting practice";
}

}

```

<MyApp.java 참고>

```java

package com.luv2code.springdemo;

public class MyApp {
public static void main(String[] args) {

//create the object
Coach theCoach = new BaseballCoach();

//use the object
System.out.println(theCoach.getDailyWorkout());
}

}

```

그리고 refactoring code 하기 위해서 인터페이스 Coach 정의

```java

package com.luv2code.springdemo;

public interface Coach {

public String getDailyWorkout();

}

```

Coach interface를 implements한 BaseballCoach 클래스

```java

package com.luv2code.springdemo;

public class BaseballCoach implements Coach {
@Override
public String getDailyWorkout() {
return "Spend 30 minutes on batting practice";
}

}

```

아래-inteface를 사용한 MyApp.java 클래스

ch20

TrackCoach 클래스 추가

일단 자바 MyApp 클래스의 main 함수 내부는

```java

public class MyApp {
public static void main(String[] args) {

//create the object
Coach theCoach = new TrackCoach();public class MyApp {
public static void main(String[] args) {

//create the object
Coach theCoach = new TrackCoach();

```

이렇게 바꿔준다.

<TrackCoach.java>

```java

package com.luv2code.springdemo;

public class TrackCoach implements Coach {

@Override
public String getDailyWorkout() {
return "Run a hard 5k";
}

}

```

<MyApp.java>

```java

package com.luv2code.springdemo;

public class MyApp {
public static void main(String[] args) {

//create the object
Coach theCoach = new TrackCoach();

//use the object
System.out.println(theCoach.getDailyWorkout());
}

}

```

ch23 Inversion of Control

일단 세팅

applicationContext.xml 복사

xml 파일을 복사 붙여넣기 한 예

Step1: Configure your Spring Beans

Spring Beans를 configure 하기 위해서 코드를 쓰자면

Copy>Pase한 파일에 id와 fullyqualified class name을 넣어준다.

여기서 "id"인 "myCoach"는 별칭 같은 거고, class=~~에 들어갈 것은 implementation class의 full name이다.

"id"인 "myCoach"는 어떻게 쓰일까? 별칭 같은거라는데...?

<applicationContext.xml>

```java


<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">


```

main 함수를 포함하는 SpringHelloApp 만들기

그러고 Spring a new class: SpringHelloApp을 하나 만든다. SpringHelloApp 클래스는 main 함수가 들어있다.

우리가 대략적으로 어떤 것을 해야 하냐면

```java

package com.luv2code.springdemo;

public class HelloSpringApp {

public static void main(String[] args) {

// load the spring configuration file

// retrieve bean from spring container

// call methods on the bean

// close the context

//를 해야한다.
}
}

```

Step2: Create a Spring container

스프링 콘테이너 만들

```java

public class HelloSpringApp {

public static void main(String[] args) {

// load the spring configuration file
ClassPathXmlApplicationContext context=
new ClassPathXmlApplicationContext("applicationContext");

// load the spring configuration file

```

빨간 밑줄이 떴을 때 해결 방법

```java

import org.springframework.context.support.ClassPathXmlApplicationContext;

```

이렇게 import를 해준다.

Step 3: Retrieve bean from Spring container

```java

// retrieve bean from spring container
Coach theCoach = context.getBean("myCoach", Coach.class);

```

여기서 "myCoach"는 bean id이고 Coach.class는 interface다.

그 다음은 call methods on the bean하고 close the context하는 코드까지 짜면

```java

package com.luv2code.springdemo;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class HelloSpringApp {

public static void main(String[] args) {

// load the spring configuration file
ClassPathXmlApplicationContext context=
new ClassPathXmlApplicationContext("applicationContext");

// retrieve bean from spring container
Coach theCoach = context.getBean("myCoach", Coach.class);

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

// close the context
context.close();
}
}

```

그러고 Run as... 을 누르면 다음과 같이

Loading XML bean definitions from class path resource [applicationContext.xml]이 뜨고

Run a hard 5k의 출력 결과가 나온다.

ch24 configuration 파일을 change 해보자!

```java


```

TrackCoach

그러면 TrackCoach에 걸맞게 나온다.


FAQ: Why do we specify the Coach interface in getBean()?

Question

Why do we specify the Coach interface in getBean()?

For example:

Coach theCoach = context.getBean("myCoach", Coach.class);

---

Answer

When we pass the interface to the method, behind the scenes Spring will cast the object for you.

context.getBean("myCoach", Coach.class)

However, there are some slight differences than normal casting.

From the Spring docs:

Behaves the same as getBean(String), but provides a measure of type safety by throwing a BeanNotOfRequiredTypeException if the bean is not of the required type. This means that ClassCastException can't be thrown on casting the result correctly, as can happen with getBean(String).

Source: http://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/beans/factory/BeanFactory.html#getBean-java.lang.String-java.lang.Class-

Practice Activity #1 - Inversion of Control with XML Configuration

Define a new implementation for the Coach interface. You can use whatever sport you would like.

Reference your new implementation in the Spring config file.

Test your application to verify you are retrieving information from your new Coach implementation.

You can check your code against the solution. The solution is available here:

728x90

관련글 더보기

댓글 영역