본문 바로가기
Today I Learned/Spring

[Spring] 어디에서나 Spring 컨테이너 Bean 객체 가져오기

by dbs_ 2023. 2. 14.

 

의문

회사에서 코드를 짜던 중 component, controller, service, mapper등이 아니라서 마음대로 @autowired, @resource 등을 해서 가져다가 쓸 수 없었다. 그래서 bean 등록이 안되는 부분에 mapper, service등을 가져와 사용하고 싶을 때는 어떻게 해야할까? 

TestMapper mapper = (TestMapper) ApplicationContextProvider.getApplicationContext().getBean("testMapper");
List<Map> List = mapper.test();
WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext());
								TestMapper testMapper = (TestMapper) ctx.getBean("testMapper");