ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Spring MVC - ApplicationScope 빈 주입
    Spring/Spring MVC 2021. 12. 30. 02:02
    반응형

    ApplicationScope

    • Bean을 정의할 때 ApplicationScope로 정의하면 서버가 가동될 때 자동으로 주입
    • 주입된 Bean은 주입만 이루어지는 것이므로 application 영역에 저장되지 않는다.
    • 서버가 가동될 때 자동 주입 되는 것이므로 @Lazy를 설정하지 않아도 된다.

     


     

    방법 1 - java, ApplicationScope으로 Bean 주입

     

    @Configuration에서 ApplicationScope으로 Bean 주입

     하나는 Bytypte으로 또 다른 하나는 Byname으로 쓰기 위해 두 개의 Bean들을 정의한다. 

    // 프로젝트 작업시 사용할 bean을 정의하는 클래스
    @Configuration
    public class RootAppContext {
    
    	@Bean
    	@ApplicationScope
    	public DataBean1 applicationBean1() {
    		return new DataBean1();
    	}
    	
    	@Bean("applicationBean2")
    	@ApplicationScope
    	public DataBean2 applicationBean2() {
    		return new DataBean2();
    	}
    }

     

    @Controller
    public class testController {
    
    	@Autowired
    	DataBean1 applicationBean1;
    	
    	@Resource(name = "applicationBean2")
    	DataBean2 applicationBean2;
    	
    	@GetMapping("/test1")
    	public String test1() {
    		
    		applicationBean1.setData1("data1");
    		applicationBean1.setData2("data2");
    		applicationBean2.setData3("data3");
    		applicationBean2.setData4("data4");
    		
    		return "test1";
    	}
    	
    	@GetMapping("/result1")
    	public String result1() {
    		
    		System.out.println(applicationBean1.getData1());
    		System.out.println(applicationBean1.getData2());
    		System.out.println(applicationBean2.getData3());
    		System.out.println(applicationBean2.getData4());
    
    		return "result1";
    	}
    }
    @Autowired
    DataBean1 applicationBean1;
     -  RootContext.java 에서 정의한 bean을 Bytype으로 주입한다. 

    @Resource(name = "applicationBean2")
    DataBean2 applicationBean2;
     - RootContext.java 에서 정의한 bean을 Byname으로 주입한다.
     - Byname으로 정의한 Bean은 자동으로 Application 영역에 저장된다.(JSP에서 사용 가능)

     마찬가지로 객체를 Controller에 주입했을 뿐이지 Application 영역에 저장하지 않은 상태이다.

    JSP에서 사용하기 위해서는 Request나 Application 영역에 저장에 저장하면 된다.

     


     

    @Component으로 정의한 Bean 주입

     우선 @Conponent를 이용해 Bean을 정의한다.

    @Component
    @ApplicationScope
    public class DataBean3 {
    	
    	private String data5;
    	private String data6;
    	
        // .... getter, setter
    }
    @Component(value = "applicationBean4")
    @ApplicationScope
    public class DataBean4 {
    
    	private String data7;
    	private String data8;
    	// .... getter, setter
    }

     하나는 Bytype으로 가져오기 위해 이름을 정해주지 않았고, 다른 하나는 Byname으로 가져오기 위해 이름을 정해줬다. 이제 @Component로 정의한 Bean을 사용할 수 있도록 SevletAppContext.java 에 스캔 패키지를 지정해준다.

     

    // Spring MVC 프로젝트에 관련된 설정을 하는 클래스
    @Configuration
    // Controller 어노테이션이 셋팅되어 있는 클래스를 Controller로 등록한다.
    @EnableWebMvc
    // 스캔할 패키지를 지정한다.
    @ComponentScan("kr.co.controller")
    @ComponentScan("kr.co.beans")
    public class ServletAppContext implements WebMvcConfigurer{
    	// Controller의 메서드가 반환하는 jsp의 이름 앞뒤에 경로와 확장자를 붙혀주도록 설정한다.
    	@Override
    	public void configureViewResolvers(ViewResolverRegistry registry) {
    		....
    	}
    	
    	// 정적 파일의 경로를 매핑한다.
    	@Override
    	public void addResourceHandlers(ResourceHandlerRegistry registry) {
    		....
    	}
    }
    @ComponentScan("kr.co.softcampus.beans")
     - @component 로 정의한 Bean들을 사용할 수 있도록 @Component를 찾기 위해 스캔해준다.

     

     마지막으로 Controller에서 주입받아 사용하면 된다.

    @Controller
    public class testController {
    
    	@Autowired
    	DataBean3 applicationBean3;
    	
    	@Resource(name = "applicationBean4")
    	DataBean4 applicationBean4;
    	
    	@GetMapping("/test1")
    	public String test1() {
    
    		applicationBean3.setData5("data5");
    		applicationBean3.setData6("data6");
    		applicationBean4.setData7("data7");
    		applicationBean4.setData8("data8");
    		
    		return "test1";
    	}
    	
    	@GetMapping("/result1")
    	public String result1() {
    
    		System.out.println(applicationBean3.getData5());
    		System.out.println(applicationBean3.getData6());
    		System.out.println(applicationBean4.getData7());
    		System.out.println(applicationBean4.getData8());
    		
    		return "result1";
    	}
    }
    @Autowired
    DataBean3 applicationBean3;
     - @Component 로 정의한 Bean을 Bytype으로 주입

    @Resource(name = "applicationBean4")
    DataBean4 applicationBean4;
     - @Component 로 정의한 Bean을 Byname으로 주입

     마찬가지로 객체를 Controller에 주입했을 뿐이지 application 영역에 저장하지 않은 상태이다.

    JSP에서 사용하기 위해서는 request나 application 영역에 저장에 저장하면 된다.

     

     


    방법 2 - xml, ApplicationScope으로 Bean 주입

     

    @Configuration에서 ApplicationScope으로 Bean 주입

     하나는 Bytypte으로 또 다른 하나는 Byname으로 쓰기 위해 두 개의 Bean들을 정의한다. 

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
    	   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    	   xsi:schemaLocation="http://www.springframework.org/schema/beans
    	   					   http://www.springframework.org/schema/beans/spring-beans.xsd">
    	   <bean class='kr.co.softcampus.beans.DataBean1' scope='application'/>
    	   <bean class='kr.co.softcampus.beans.DataBean2' id = 'sessionBean2' scope='application'/>		   
    </beans>
    scope = 'application'
     - 이 Bean을 Application Scope로 주입 설정

     

    @Controller
    public class testController {
    
    	@Autowired
    	DataBean1 applicationBean1;
    	
    	@Resource(name = "applicationBean2")
    	DataBean2 applicationBean2;
    	
    	@GetMapping("/test1")
    	public String test1() {
    		
    		applicationBean1.setData1("data1");
    		applicationBean1.setData2("data2");
    		applicationBean2.setData3("data3");
    		applicationBean2.setData4("data4");
    		
    		return "test1";
    	}
    	
    	@GetMapping("/result1")
    	public String result1() {
    		
    		System.out.println(applicationBean1.getData1());
    		System.out.println(applicationBean1.getData2());
    		System.out.println(applicationBean2.getData3());
    		System.out.println(applicationBean2.getData4());
    		
    		return "result1";
    	}
    }
    @Autowired
    DataBean1 applicationBean1;
     - root-context.xml 에서 정의한 Bean 을 Bytype으로 주입
     - 서버가 시작될 때 주입이 이루어지므로 @Lazy를 안써도 된다.

    @Resource(name = "applicationBean2")
    DataBean2 applicationBean2;
     - root-context.xml 에서 정의한 Bean을 Byname으로 주입
     - 자동으로 application 영역에 저장
     - 서버가 시작될 때 주입이 이루어지므로 @Lazy를 안써도 된다.

     마찬가지로 Bytype으로 주입한 Bean은 Controller에 주입했을 뿐이지 application 영역에 저장하지 않은 상태이다.

    JSP에서 사용하기 위해서는 request나 application 영역에 저장에 저장하면 된다.

     


    @Component으로 정의한 bean 주입

     우선 @Component를 이용해 방법 1과 같이 Bean을 정의해준다.(생략하겠다). Bean을 정의해주면 @Component로 정의한 Bean을 사용할 수 있도록 sevlet-context.xml 에 스캔 패키지를 지정해준다.

    <?xml version="1.0" encoding="UTF-8"?>
    <beans:beans xmlns="http://www.springframework.org/schema/mvc"
    			 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    			 xmlns:beans="http://www.springframework.org/schema/beans"
    			 xmlns:context="http://www.springframework.org/schema/context"
    			 xsi:schemaLocation="http://www.springframework.org/schema/mvc
    			 		     http://www.springframework.org/schema/mvc/spring-mvc.xsd
    			 		     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">
    			 					 
    	<!-- 스캔한 패지키 내부의 클래스 중 Controller 어노테이션을 가지고 있는 클래스들을 Controller로 로딩하도록 한다 -->
    	<annotation-driven/>
    	
    	<!-- 스캔할 bean들이 모여있는 패키지를 지정한다. -->
    	<context:component-scan base-package="kr.co.softcampus.controller"/>
    	<context:component-scan base-package="kr.co.softcampus.beans"/>
    	
    	<!-- Controller의 메서드에서 반환하는 문자열 앞 뒤에 붙힐 경로 정보를 셋팅한다. -->
    	<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>
    	
    	<!-- 정적파일(이미지, 사운드, 동영상, JS, CSS 등등) 경로 셋팅 -->
    	<resources mapping="/**" location="/resources/"/>
    	 
    </beans:beans>
    <context:component-scan base-package="kr.co.softcampus.beans"/>
     - @component 로 정의한 Bean들을 사용할 수 있도록 @Component를 찾기 위해 스캔해준다.

     

     이제 Controller에서 사용해주면 된다.

    @Controller
    public class testController {
    
    	@Autowired
    	DataBean3 applicationBean3;
    	
    	@Resource(name = "applicationBean4")
    	DataBean4 applicationBean4;
    	
    	@GetMapping("/test1")
    	public String test1() {
    
    		applicationBean3.setData5("data5");
    		applicationBean3.setData6("data6");
    		applicationBean4.setData7("data7");
    		applicationBean4.setData8("data8");
    		
    		return "test1";
    	}
    	
    	@GetMapping("/result1")
    	public String result1() {
    
    		System.out.println(applicationBean3.getData5());
    		System.out.println(applicationBean3.getData6());
    		System.out.println(applicationBean4.getData7());
    		System.out.println(applicationBean4.getData8());
    
    		return "result1";
    	}
    }
    @Autowired
    DataBean3 applicationBean3;
     - @Component 로 정의한 Bean을 Bytype으로 주입

    @Resource(name = "applicationBean4")
    DataBean4 applicationBean4;
     - @Component 로 정의한 Bean을 Byname으로 주입

     마찬가지로 Bytype으로 주입한 Bean은 Controller에 주입했을 뿐이지 application 영역에 저장하지 않은 상태이다. jsp에서 사용하기 위해서는 request나 application 영역에 저장에 저장하면 된다.

    반응형

    'Spring > Spring MVC' 카테고리의 다른 글

    Spring MVC - Properties  (0) 2021.12.30
    Spring MVC - Cookie  (0) 2021.12.30
    Spring MVC - ApplicationScope  (0) 2021.12.29
    Spring MVC - SessionScope 빈 주입  (0) 2021.12.29
    Spring MVC - Session  (0) 2021.12.29

    댓글

Designed by Tistory.