HelloWorld版的SpringMVC使用註解驅動的依賴注入

李秀才發表於2016-03-04

       使用註解,可以極大的減少Spring配置檔案的書寫,方便實用。接下來看一個最簡單的註解方式的依賴注入的使用。

首先在spring-servlet.xml裡啟用註解:

 <mvc:annotation-driven />

啟用包掃描功能,以便spring將使用註解的類註冊為spirng的bean:

 <context:component-scan base-package="com.mvc.rest" />

註解各類的功能

介面類:

package com.mvc.rest.service;

public interface ITestService {
     public String testMethod();
}
實現類:

package com.mvc.rest.service;

import org.springframework.stereotype.Service;

@Service
public class TestService implements ITestService{
	@Override
	public String testMethod() {
		return "Hello World!";
	}
}

用@Resource註解啟用註解:

package com.mvc.rest.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.mvc.rest.service.ITestService;

@Controller  
public class RestConstroller {  
    @Resource
    private ITestService testService;
    public RestConstroller() {}  
    @RequestMapping(value = "/welcome", method = RequestMethod.GET)  
    public String welcome() {  
    	String hello=testService.testMethod();
    	System.out.println("hello:======"+hello);
        return "/welcome";  
    }  
}
如此便實現了註解方式的依賴注入。



相關文章