뚜벅이

Spring의 @Resource 간단히 써보기 ( 토비의 스프링 학습내용 적용해보기) 본문

Java Spring 조각자료

Spring의 @Resource 간단히 써보기 ( 토비의 스프링 학습내용 적용해보기)

ZZM 2021. 7. 4. 22:58

 implements ApplicationContextAware 

ACA 라는 녀석은 . > AC 를 세팅값으로 넘겨받아서.  이것 위에있는 빈들을 가져올수있는 겟빈 등등이 가능한 컨텍스트를 심겨둔 녀석.  스프링 시동과정에서 껴들어오는 친구이다. 

 

기존코드 

package com.admin.service;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class Provider implements ApplicationContextAware  {


	ApplicationContext context;
	
	
	
	public ApplicationContext getContext() {
		return context;
	}



	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		context = applicationContext;
	}
	
}

 

나의 예상 1  )  setApplicationContext 는 ACA 에 있는것이다. 

즉  AC가  스프링에 탑재 (?)  시동걸릴때(?)  이 메서드 작동할 것이라 예상했다. 

 

@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {

System.out.println(
"\n불러온다 컨텍스트+"
+ "\n불러온다 컨텍스트+"
+ "\n불러온다 컨텍스트+"
+ "\n불러온다 컨텍스트+"
+ "\n불러온다 컨텍스트+");

를 넣어주었더니 역시 콘솔에 

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::                (v2.4.5)

2021-07-04 22:50:54 INFO com.MoviePApplication[logStarting:55] - Starting MoviePApplication using Java 15.0.2 on DESKTOP-U03VV1N with PID 23788 (C:\Users\unoes\git\movieProj\movieP\target\classes started by unoes in C:\Users\unoes\git\movieProj\movieP)
2021-07-04 22:50:54 DEBUG com.MoviePApplication[logStarting:56] - Running with Spring Boot v2.4.5, Spring v5.3.6
2021-07-04 22:50:54 INFO com.MoviePApplication[logStartupProfileInfo:675] - No active profile set, falling back to default profiles: default
2021-07-04 22:50:56 DEBUG com.zaxxer.hikari.HikariConfig[attemptFromContextLoader:946] - Driver class net.sf.log4jdbc.sql.jdbcapi.DriverSpy found in Thread context class loader org.springframework.boot.devtools.restart.classloader.RestartClassLoader@30188c69

불러온다 컨텍스트+
불러온다 컨텍스트+
불러온다 컨텍스트+
불러온다 컨텍스트+
불러온다 컨텍스트+
2021-07-04 22:50:57 DEBUG _org.springframework.web.servlet.HandlerMapping.Mappings[detectHandlerMethods:294] - 
	c.a.s.MovieTimedeleteReg:

로 찍히는 것이 확인 되었다.   스프링 실행시점 완전 극초반이다. ㄷㄷ

 

여튼! 

 책읽고나서 이클래스를  수정 해보았다. 

어차피 불러올게 AC 라면    @Resource 써서 불러와도 되지않을까라는 생각이었다. 

(  내딴으로 저질러본 심산 ::

"@Resource 라는 어놋을 붙이면   어차피 단일 AC를 가지는 이 조그만 프로젝트에서 불러지는 컨텍스트는 뻔할것이다"

라고 전제를 하고  이렇게 바꾸어 보았다. )

package com.admin.service;
import javax.annotation.Resource;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class Provider{
	@Resource
	ApplicationContext context;
	
	
	
	public ApplicationContext getContext() {
		return context;
	}
//	@Override
//	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
//		context = applicationContext;
//	}
	
	// 되돌리기 
	//1   @Resource 어노테이션 제거 
	//2   implements ApplicationContextAware  붙여주기 
	//3  오버라이드 살려서 구현체 살려주기 ( 필수 property 값 먹여주기) > context 를 장착시킨다. 
	//4  그것이   AppCtxtAware 정체성이므로
}

 

 

다행히 통했다! 

이 프로바이더로 겟컨텍스트  하고   .  getBean 어쩌구해서 서비스를 팽팽팽 돌려주게되는 그림은 @Controller 내부에서 나오게 된다. 

 

 

컨트롤러 소스에  provider 사용례

@Controller
@RequestMapping("admin/persqna/{service}")
public class PersqnaController {
	
	@Resource
	Provider pr;
	
	
	
	@ModelAttribute("data")
	Object data(@PathVariable String service, HttpServletRequest request
			,ServiceNoticePageDTO snpdto
			,ServiceFullDTO sfdto
			) {
		
		PageeditService sr = pr.getContext().getBean("persqna"+service,PageeditService.class);

sr. execute 돌겠지  당연히  data 메서드 매개변수들 request 나등등 것들의 내용들 받아서말이다. 그서비스 빈 안에는 db 관련한 작업을 하는것도 있을것이고 그건 또 mappper 에 있겠지 mybatis 관련 xml 파일에는 실제 쿼리도있을것이고 등등등 ..