강의/Java Spring Boot

CDI, XML 겉핣기

studylida 2024. 7. 29. 21:00

CDI에 대해 정말 간단하게 알아보자.

CDI는 인터페이스로, 구현이 없고, Spring Framework에서 구현된다.

우리가 알아야 할 건 두 가지다.

1. Inject는 Autowired와 비슷한 기능을 하고, 
2. Named는 Component와 비슷한 기능을 한다.

끝.

xml에 대해 알아보자.

지금까지 우리는 Java 설정을 이용했지만, 전통적인 Spring에는 Java 설정이 없어 xml을 사용했다.

코드를 작성하며 xml에 대해 알아보자.

일단 언제나 그랬던 것처럼 기반 클래스를 만들자. 기반 클래스의 이름은 XmlConfigurationContextLauncherApplication라고 하자.

지금까지는 @Configuration을 사용해왔다. 이는 Java 설정을 사용함을 의미한다. 이번 시간에는 XML 설정 파일을 사용할 예정이니 @Configuration을 사용하지 않는다.

일단 xml 파일을 만들어보자. src/main/resoruces에 만들 것이다. 이름은 contextConfiguration으로 하자.

처음 만들면 뭘 해야 할지 모를텐데, 검색엔진에 Spring xml configuration example 과 같은 걸 검색하면 XML Schema-based configuration 같은 페이지를 볼 수 있다. 여기서 context schema를 검색하면 간단한 XML 예시를 확인할 수 있다.

이렇게 찾은 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"> <!-- bean definitions here -->

</beans>

그리고 실행해보자. 아마 오류가 날 것이다. 왜냐하면 지금까지는 Java 설정을 사용했기에 AnnotationConfigApplicationContext를 사용했는데, 이는 Java 설정을 실행하는데 사용되기 때문이다.

대신에 try(var context = new ClassPathXmlApplicationContext("contextConfiguration.xml"))를 사용하자.

public class XmlConfigurationContextLauncherApplication {

    public static void main(String[] args) {

        try(var context =
                    new ClassPathXmlApplicationContext("contextConfiguration.xml")) {
            // Use the ClassPathXml class when you want to run something related to xml.

            Arrays.stream(context.getBeanDefinitionNames())
                    .forEach(System.out::println);

        }
    }
}

이렇게 코드를 작성하고 실행하면 당연하지만 Bean이 없기 때문에 출력되는 Bean 이 없다.

그렇다면 XML context에서느 Bean을 어떻게 정의해야할까? 우리는 xml 파일에서 Bean을 정의할 수 있다.

<beans...>

    <bean id="name" class="java.lang.String">
        <constructor-arg value="Ranga" />
    <bean>
    <bean id="age" class="java.lang.Integer">
        <constructor-arg value="35" />
    <bean>

</beans>

위와 같이 코드를 작성하고 어플리케이션을 실행하면 빈이 출력되는 걸 확인할 수 있다.

<context:component-scan base-package="com.in28minutes.learn_spring_framework.game"/>을 통해 컴포넌트를 스캔할 패키지를 설정할 수 있다.

다만 이렇게 할 경우 스캔한 패키지에 정의된 모든 bean을 가져오게 된다. 때문에 일부만 가져오고 싶은 경우 Bean을 따로 정의해야 한다. 방법은 아래와 같다.

    <bean id="game" class="com.in28minutes.learn_spring_framework.game.PacmanGame"/>
    <bean id="gameRunner"
          class="com.in28minutes.learn_spring_framework.game.GameRunner">
        <constructor-arg ref="game"/>
    </bean>