使用注解,可以极大的减少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"; } }如此便实现了注解方式的依赖注入。