웹사이트 검색

Spring IoC, Spring Bean 예제 자습서


Spring IoC 예제 자습서에 오신 것을 환영합니다. Spring Framework는 Inversion of Control 원칙을 기반으로 합니다. 종속성 주입은 응용 프로그램에서 IoC를 구현하는 기술입니다.

스프링 IoC

  1. 스프링 IoC
  2. 봄콩
  3. 봄 콩 스코프
  4. 스프링 빈 구성
  5. Spring IoC 및 Spring Bean 예제
    1. XML 기반 Spring Bean 구성
    2. 주석 기반 Spring Bean 구성
    3. Java 기반 Spring Bean 구성

    스프링 IoC 컨테이너

    Spring IoC는 객체 종속성 간의 느슨한 결합을 달성하는 메커니즘입니다. 런타임 시 개체의 느슨한 결합 및 동적 바인딩을 달성하기 위해 개체 종속성이 다른 어셈블러 개체에 의해 주입됩니다. Spring IoC 컨테이너는 종속성을 객체에 주입하고 사용할 수 있도록 준비하는 프로그램입니다. Spring Dependency Injection을 사용하여 애플리케이션에서 IoC를 구현하는 방법을 이미 살펴보았습니다. Spring IoC 컨테이너 클래스는 org.springframework.beansorg.springframework.context 패키지의 일부입니다. Spring IoC 컨테이너는 객체 종속성을 분리하는 다양한 방법을 제공합니다. BeanFactory는 Spring IoC 컨테이너의 루트 인터페이스입니다. ApplicationContext는 Spring AOP 기능, i18n 등을 제공하는 BeanFactory 인터페이스의 하위 인터페이스입니다. ApplicationContext의 유용한 하위 인터페이스 중 일부는 입니다. >ConfigurableApplicationContextWebApplicationContext. Spring Framework는 Spring 컨텍스트와 Spring Bean을 가져오는 데 사용할 수 있는 여러 가지 유용한 ApplicationContext 구현 클래스를 제공합니다. 우리가 사용하는 유용한 ApplicationContext 구현 중 일부는 다음과 같습니다.

    • AnnotationConfigApplicationContext: 독립형 자바 애플리케이션에서 Spring을 사용하고 구성에 주석을 사용하는 경우 이를 사용하여 컨테이너를 초기화하고 빈 개체를 가져올 수 있습니다.
    • ClassPathXmlApplicationContext: 독립형 애플리케이션에 스프링 빈 구성 xml 파일이 있는 경우 이 클래스를 사용하여 파일을 로드하고 컨테이너 개체를 가져올 수 있습니다.
    • FileSystemXmlApplicationContext: xml 구성 파일을 파일 시스템의 어느 곳에서나 로드할 수 있다는 점을 제외하면 ClassPathXmlApplicationContext와 유사합니다.
    • 웹 애플리케이션용 AnnotationConfigWebApplicationContext 및 XmlWebApplicationContext.

    일반적으로 Spring MVC 애플리케이션에서 작업 중이고 애플리케이션이 Spring Framework를 사용하도록 구성된 경우 애플리케이션이 시작될 때 Spring IoC 컨테이너가 초기화되고 빈이 요청되면 종속성이 자동으로 주입됩니다. 그러나 독립 실행형 애플리케이션의 경우 애플리케이션 어딘가에서 컨테이너를 초기화한 다음 이를 사용하여 Spring Bean을 가져와야 합니다.

    봄콩

    Spring Bean은 특별한 것이 아니며 Spring 컨테이너를 통해 초기화하는 Spring 프레임워크의 모든 객체를 Spring Bean이라고 합니다. 일반적인 Java POJO 클래스는 구성 메타데이터 정보를 제공하여 컨테이너를 통해 초기화되도록 구성된 경우 Spring Bean이 될 수 있습니다.

    스프링 빈 스코프

    Spring Beans에 대해 정의된 다섯 가지 범위가 있습니다.

    1. singleton - 각 컨테이너에 대해 하나의 빈 인스턴스만 생성됩니다. 이는 Spring Bean의 기본 범위입니다. 이 범위를 사용하는 동안 Bean에 공유 인스턴스 변수가 없는지 확인하십시오. 그렇지 않으면 데이터 불일치 문제가 발생할 수 있습니다.
    2. prototype - 빈이 요청될 때마다 새 인스턴스가 생성됩니다.
    3. 요청 - 프로토타입 범위와 동일하지만 웹 애플리케이션에 사용하기 위한 것입니다. 각 HTTP 요청에 대해 빈의 새 인스턴스가 생성됩니다.
    4. 세션 - 컨테이너에 의해 각 HTTP 세션에 대해 새 빈이 생성됩니다.
    5. global-session - 포틀릿 애플리케이션을 위한 전역 세션 빈을 생성하는 데 사용됩니다.

    Spring Framework는 확장 가능하며 자체 범위도 만들 수 있습니다. 그러나 대부분의 경우 우리는 프레임워크에서 제공하는 범위를 잘 알고 있습니다.

    스프링 빈 구성

    Spring Framework는 애플리케이션에서 사용할 bean을 구성하는 세 가지 방법을 제공합니다.

    1. 주석 기반 구성 - @Scope 주석을 사용합니다.
    2. XML 기반 구성 - Spring 구성 XML 파일을 생성하여 빈을 구성합니다. Spring MVC 프레임워크를 사용하는 경우 web.xml 파일에 일부 상용구 코드를 작성하여 xml 기반 구성을 자동으로 로드할 수 있습니다.
    3. Java 기반 구성 - Spring 3.0부터 Java 프로그램을 사용하여 Spring Bean을 구성할 수 있습니다. Java 기반 구성에 사용되는 몇 가지 중요한 주석은 @Bean입니다.

    Spring IoC 및 Spring Bean 예제 프로젝트

    XML 기반 Spring Bean 구성

    MyBean은 간단한 Java POJO 클래스입니다.

    package com.journaldev.spring.beans;
    
    public class MyBean {
    
    	private String name;
    	
    	public String getName() {
    		return name;
    	}
    	public void setName(String name) {
    		this.name = name;
    	}
    	
    }
    

    스프링 구성 XML 파일

    servlet-context.xml 코드:

    <?xml version="1.0" encoding="UTF-8"?>
    <beans:beans xmlns="https://www.springframework.org/schema/mvc"
    	xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
    	xmlns:beans="https://www.springframework.org/schema/beans"
    	xmlns:context="https://www.springframework.org/schema/context"
    	xsi:schemaLocation="https://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd
    		https://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
    		https://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
    
    	<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
    	
    	<!-- Enables the Spring MVC @Controller programming model -->
    	<annotation-driven />
    
    	<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
    	<resources mapping="/resources/**" location="/resources/" />
    
    	<!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
    	<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    		<beans:property name="prefix" value="/WEB-INF/views/" />
    		<beans:property name="suffix" value=".jsp" />
    	</beans:bean>
    	
    	<context:component-scan base-package="com.journaldev.spring" />
    	
    	<beans:bean name="myBean" class="com.journaldev.spring.beans.MyBean" scope="singleton" ></beans:bean>
    	
    </beans:beans>
    

    MyBean은 범위가 싱글톤인 bean 요소를 사용하여 구성됩니다.

    주석 기반 Spring Bean 구성

    package com.journaldev.spring.beans;
    
    import org.springframework.context.annotation.Scope;
    import org.springframework.stereotype.Service;
    import org.springframework.web.context.WebApplicationContext;
    
    @Service
    @Scope(WebApplicationContext.SCOPE_REQUEST)
    public class MyAnnotatedBean {
    
    	private int empId;
    
    	public int getEmpId() {
    		return empId;
    	}
    
    	public void setEmpId(int empId) {
    		this.empId = empId;
    	}
    	
    }
    

    MyAnnotatedBean은 @Service를 사용하여 구성되고 범위는 요청으로 설정됩니다.

    스프링 IoC 컨트롤러 클래스

    HomeController 클래스는 애플리케이션의 홈 페이지에 대한 HTTP 요청을 처리합니다. WebApplicationContext 컨테이너를 통해 이 컨트롤러 클래스에 Spring 빈을 주입합니다.

    package com.journaldev.spring.controller;
    
    import java.text.DateFormat;
    import java.util.Date;
    import java.util.Locale;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.context.annotation.Scope;
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    
    import com.journaldev.spring.beans.MyAnnotatedBean;
    import com.journaldev.spring.beans.MyBean;
    
    @Controller
    @Scope("request")
    public class HomeController {
    		
    	private MyBean myBean;
    	
    	private MyAnnotatedBean myAnnotatedBean;
    
    	@Autowired
    	public void setMyBean(MyBean myBean) {
    		this.myBean = myBean;
    	}
    
    	@Autowired
    	public void setMyAnnotatedBean(MyAnnotatedBean obj) {
    		this.myAnnotatedBean = obj;
    	}
    	
    	/**
    	 * Simply selects the home view to render by returning its name.
    	 */
    	@RequestMapping(value = "/", method = RequestMethod.GET)
    	public String home(Locale locale, Model model) {
    		System.out.println("MyBean hashcode="+myBean.hashCode());
    		System.out.println("MyAnnotatedBean hashcode="+myAnnotatedBean.hashCode());
    		
    		Date date = new Date();
    		DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
    		
    		String formattedDate = dateFormat.format(date);
    		
    		model.addAttribute("serverTime", formattedDate );
    		
    		return "home";
    	}
    	
    }
    

    배포 설명자

    구성 메타데이터가 로드되고 컨텍스트가 초기화되도록 애플리케이션을 Spring Framework용으로 구성해야 합니다.

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app version="2.5" xmlns="https://java.sun.com/xml/ns/javaee"
    	xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
    	xsi:schemaLocation="https://java.sun.com/xml/ns/javaee https://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    
    	<!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
    	<context-param>
    		<param-name>contextConfigLocation</param-name>
    		<param-value>/WEB-INF/spring/root-context.xml</param-value>
    	</context-param>
    	
    	<!-- Creates the Spring Container shared by all Servlets and Filters -->
    	<listener>
    		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    	</listener>
    
    	<!-- Processes application requests -->
    	<servlet>
    		<servlet-name>appServlet</servlet-name>
    		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    		<init-param>
    			<param-name>contextConfigLocation</param-name>
    			<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
    		</init-param>
    		<load-on-startup>1</load-on-startup>
    	</servlet>
    		
    	<servlet-mapping>
    		<servlet-name>appServlet</servlet-name>
    		<url-pattern>/</url-pattern>
    	</servlet-mapping>
    
    </web-app>
    

    위의 거의 모든 구성은 STS 도구가 자동으로 생성한 상용구 코드입니다.

    Spring IoC Bean 예제 애플리케이션 실행

    이제 웹 애플리케이션을 실행하면 홈 페이지가 로드되고 콘솔에서 페이지를 여러 번 새로 고칠 때 다음 로그가 인쇄됩니다.

    MyBean hashcode=118267258
    MyAnnotatedBean hashcode=1703899856
    MyBean hashcode=118267258
    MyAnnotatedBean hashcode=1115599742
    MyBean hashcode=118267258
    MyAnnotatedBean hashcode=516457106
    

    MyBean은 싱글톤으로 구성되어 있으므로 컨테이너는 항상 동일한 인스턴스를 반환하고 해시 코드는 항상 동일합니다. 마찬가지로 각 요청에 대해 MyAnnotatedBean의 새 인스턴스가 다른 해시 코드로 생성됩니다.

    Java 기반 Spring Bean 구성

    독립 실행형 애플리케이션의 경우 주석 기반 및 XML 기반 구성을 사용할 수 있습니다. 유일한 요구 사항은 컨텍스트를 사용하기 전에 프로그램 어딘가에서 컨텍스트를 초기화하는 것입니다.

    package com.journaldev.spring.main;
    
    import java.util.Date;
    
    public class MyService {
    
    	public void log(String msg){
    		System.out.println(new Date()+"::"+msg);
    	}
    }
    

    MyService는 몇 가지 메서드가 있는 간단한 Java 클래스입니다.

    package com.journaldev.spring.main;
    
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.context.annotation.Configuration;
    
    @Configuration
    @ComponentScan(value="com.journaldev.spring.main")
    public class MyConfiguration {
    
    	@Bean
    	public MyService getService(){
    		return new MyService();
    	}
    }
    

    Spring 컨테이너를 초기화하는 데 사용될 주석 기반 구성 클래스입니다.

    package com.journaldev.spring.main;
    
    import org.springframework.context.annotation.AnnotationConfigApplicationContext;
    
    public class MyMainClass {
    
    	public static void main(String[] args) {
    		
    		AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(
    				MyConfiguration.class);
    		MyService service = ctx.getBean(MyService.class);
    		
    		service.log("Hi");
    		
    		MyService newService = ctx.getBean(MyService.class);
    		System.out.println("service hashcode="+service.hashCode());
    		System.out.println("newService hashcode="+newService.hashCode());
    		ctx.close();
    	}
    
    }
    

    AnnotationConfigApplicationContext 컨텍스트를 초기화한 다음 getBean() 메서드를 사용하여 MyService의 인스턴스를 가져오는 간단한 테스트 프로그램입니다. 내가 getBean 메소드를 두 번 호출하고 해시코드를 인쇄하고 있음을 주목하십시오. MyService에 대해 정의된 범위가 없으므로 싱글톤이어야 하며 따라서 해시 코드는 두 인스턴스에 대해 동일해야 합니다. 위의 애플리케이션을 실행하면 이해를 확인하는 다음 콘솔 출력이 표시됩니다.

    Sat Dec 28 22:49:18 PST 2013::Hi
    service hashcode=678984726
    newService hashcode=678984726
    

    XML 기반 구성을 찾고 있다면 Spring XML 구성 파일을 만든 다음 다음 코드 조각으로 컨텍스트를 초기화하십시오.

    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
                    "applicationContext.xml");
            MyService app = context.getBean(MyService.class);
    

    Spring IoC 예제 자습서, Spring Bean 범위 및 구성 세부 정보는 여기까지입니다. 아래 링크에서 Spring IoC 및 Spring Bean 예제 프로젝트를 다운로드하고 더 나은 이해를 위해 사용해보십시오.

    Spring Beans 프로젝트 다운로드

    참조: IOC용 Spring.IO 페이지