본문 바로가기
Spring

객체 DI Annotation으로 변경

by 영카이브 2024. 3. 3.

객체 DI Annotation으로 변경하기

 

해당 설정을 주석 처리하였다. 즉 DI한것을 주석처리한것이다. 

    <bean name="/notice/list" class="com.newlecture.web.controller.notice.ListController">
    	<!-- 이제 set되는 자료형이 클래스가 아니라 인터페이스다. -->
    	<!-- <property name="service" ref="noticeService" /> -->
    </bean>

 

ListController.java에서 @Autowired 어노테이션을 붙이는 것으로 변경하였다. 

@Autowired
private NoticeService noticeService;

 

이 @Autowired 어노테이션을 사용하기위해 servlet-context.xml에 추가하였다. 

xmlns:context="http://www.springframework.org/schema/context"

xsi:schemaLocation= 에 아래 추가
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd

<context:annotation-config />

 

 

 

Annotation으로 서비스 객체 생성

@Component는 Spring의 컴포넌트 스캔에 의해 빈으로 등록하라는 것을 나타낸다.
따라서 스캔범위내의 어노테이션이 붙어있는 클래스들은 객체로 만들어서 IOC컨테이너에 담아진다.(등록된다.)
이 스캔 범위는 패키지명이며 범위 내의 어노테이션이 붙은 클래스들은 객체화된다. 

<context:component-scan base-package="com.newlecture.web.service" />

@Service
public class JDBCNoticeService implements NoticeService{

 

com.newlecture.web.service 를 지정해주면 해당패키지 안에 있는 모든 클래스들을 스캔하게 된다.

어노테이션이 붙은것은 자연스럽게 찾는 기능이 이미 있기 때문에 <context:annotation-config /> 는 삭제한다.

@Component는 또한 세분화된 역할을 하는 세 개의 특별한 어노테이션의 상위 개념이다.

  • @Controller: Spring MVC에서 웹 요청을 처리하는 컨트롤러 클래스를 지정
  • @Service: 비즈니스 로직을 수행
  • @Repository: 데이터 액세스를 담당

 

Annotataion으로 URL 매핑

기존 IndexController.java

public class IndexController implements Controller{

	@Override
	public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// 콘솔에 "index controller" 출력
		System.out.println("index controller");
		
		// ModelAndView 객체 생성
		ModelAndView mv = new ModelAndView("root.index");
		
		// "data"라는 키와 "Hello Spring MVC"라는 값을 추가
		mv.addObject("data", "Hello Spring MVC");
		
		// 뷰 이름을 "index.jsp"로 설정
		//mv.setViewName("WEB-INF/view/index.jsp");

		// ModelAndView 객체 반환
		return mv;
	}	
}

 

@Controller를 써서 바꿔보겠다. 

 

기존 servlet-context.xml

<?xml version="1.0" encoding="UTF-8"?>
<!-- 디스패처 서블릿 설정 -->
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:context="http://www.springframework.org/schema/context"
    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
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">
        
	<context:annotation-config />
    
    <!-- IndexController 빈 설정 -->
    <bean name="/index" class="com.newlecture.web.controller.IndexController" />  
    
    <!-- ListController 빈 설정 -->
    <bean name="/notice/list" class="com.newlecture.web.controller.notice.ListController">
    </bean>  
    
    <!-- DetailController 빈 설정 -->
	<bean name="/notice/detail" class="com.newlecture.web.controller.notice.DetailController" />  
    
    <!-- ViewResolver 설정 -->
    <bean class="org.springframework.web.servlet.view.UrlBasedViewResolver">
		<property name="viewClass" value="org.springframework.web.servlet.view.tiles3.TilesView" />
		<!-- 뷰리졸버보다 우선순위를 높게하였다. -->
		<property name="order" value="1" />
	</bean>
	
	<!-- TilesConfigurer 설정 -->
	<bean class="org.springframework.web.servlet.view.tiles3.TilesConfigurer">
		<property name="definitions" value="/WEB-INF/tiles.xml" />
	</bean>
    
    <!-- InternalResourceViewResolver 설정 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    	<!-- 뷰 파일 위치의 접두사 설정 -->
    	<property name="prefix" value="/WEB-INF/view/"></property>
    	<!-- 뷰 파일 확장자 설정 -->
    	<property name="suffix" value=".jsp"></property>
    	<property name="order" value="2" />
    </bean>
    
    <!-- 리소스 핸들러 설정 -->
    <mvc:resources location="/static/" mapping="/**"></mvc:resources> 
</beans>

 

수정 후 servlet-context.xml

<context:component-scan base-package="com.newlecture.web.controller" />

<!-- <bean name="/index" class="com.newlecture.web.controller.IndexController" /> -->

<mvc:annotation-driven /> // name="/index" 이것을 @RequestMapping으로 받는다. 

<?xml version="1.0" encoding="UTF-8"?>
<!-- 디스패처 서블릿 설정 -->
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:context="http://www.springframework.org/schema/context"
    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
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">
        
	<context:component-scan base-package="com.newlecture.web.controller" />
    
    <!-- IndexController 빈 설정 -->
    <!-- <bean name="/index" class="com.newlecture.web.controller.IndexController" />   -->
    
    <!-- ListController 빈 설정 -->
    <bean name="/notice/list" class="com.newlecture.web.controller.notice.ListController">
    </bean>  
    
    <!-- DetailController 빈 설정 -->
	<bean name="/notice/detail" class="com.newlecture.web.controller.notice.DetailController" />  
    
    <!-- ViewResolver 설정 -->
    <bean class="org.springframework.web.servlet.view.UrlBasedViewResolver">
		<property name="viewClass" value="org.springframework.web.servlet.view.tiles3.TilesView" />
		<!-- 뷰리졸버보다 우선순위를 높게하였다. -->
		<property name="order" value="1" />
	</bean>
	
	<!-- TilesConfigurer 설정 -->
	<bean class="org.springframework.web.servlet.view.tiles3.TilesConfigurer">
		<property name="definitions" value="/WEB-INF/tiles.xml" />
	</bean>
    
    <!-- InternalResourceViewResolver 설정 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    	<!-- 뷰 파일 위치의 접두사 설정 -->
    	<property name="prefix" value="/WEB-INF/view/"></property>
    	<!-- 뷰 파일 확장자 설정 -->
    	<property name="suffix" value=".jsp"></property>
    	<property name="order" value="2" />
    </bean>
    
    <!-- 리소스 핸들러 설정 -->
    <mvc:resources location="/static/" mapping="/**"></mvc:resources>
    <mvc:annotation-driven /> 
</beans>

 

수정 후 IndexController.java
URL이 클래스 이름에 매핑되는것이 아니라 함수에 매핑되는 것을 볼 수 있다. 
@Controller
public class IndexController{
	
	@RequestMapping("/index") // URL 매핑
	public void aaa() {
		System.out.println("asdf");
	}
}
 
 
따라서 아래와 같은 코드도 가능하다. 
@Controller
public class IndexController{
	
	@RequestMapping("/index")
	public void aaa() {
		System.out.println("asdf");
	}
	
	@RequestMapping("/help")
	public void bbb() {
		System.out.println("help");
	}
}

 

다른 url도 매핑가능함으로 IndexController보다 더 광범위한 표현이 필요하다. 따라서 HomeController가 적절하다. 

 

HomeController 만들기

 

뷰 정보에 대한 내용은 문자열로 반환한다. 

@Controller
@RequestMapping("/")
public class HomeController{
	
	@RequestMapping("index")
	public String index() {
		// 뷰 페이지를 만들기 위해 문자열로 return 
		return "root.index";
	}
}

 

이처럼 ListController와 Detailcontroller를 따로 만들지 않고 NoticeController로 묶어주었다. 

공통 데이터인 private NoticeService noticeService; 를 선언한다.

@Controller
@RequestMapping("/customer/notice/") // 공통경로는 한번만 쓰도록 빼줌 
public class NoticeController {
	
	
	@Autowired
	private NoticeService noticeService; 
	
	@RequestMapping("list")
	public String list() throws ClassNotFoundException, SQLException {
		List<Notice> list = noticeService.getList(1, "TITLE", ""); 
		return "notice.list"; 
	}
	
	@RequestMapping("detail")
	public String detail() {
		return "notice.detail";
	}
}

 

 

 

 

 

참고 자료 출처:(51~56)

https://www.youtube.com/watch?v=idmX4yP-6Ps&list=PLq8wAnVUcTFUHYMzoV2RoFoY2HDTKru3T&index=51