2.通过配置文件注入的方法 马克-to-win:上面的注入方法是通过@Service的注解方法。类似的还有@Repository、@Component、@Constroller,功能大体一样,就是实例化以后放到Spring容器当中接受管理。当然你肯定乐意在service类前放@Service而不愿意放@Repository而故意迷惑自己。另外注意,缺省的情况都是单态的。(省我们事了,但要注意线程安全)。除了注解注入,我们还有配置文件的方法来注入。相比注解的方法来讲,配置文件的方法比较集中,但缺乏灵活性。怎么讲呢?a处和b处想按不同的方式来处理?不行。因为统一一个地方处理。a和b必须统一,所以缺少了灵活性。 例 1.2 package com; import javax.annotation.Resource; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.WebApplicationContextUtils; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.support.RequestContextUtils; import service.interfac.ILoginService; @Controller public class HelloWorldController { private ILoginService loginServic; @RequestMapping("/helloa") public ModelAndView helloWorld(HttpServletRequest request, HttpServletResponse response, HttpSession sesssion) { ServletContext sc=RequestContextUtils.getWebApplicationContext(request).getServletContext(); WebApplicationContext wac=WebApplicationContextUtils.getRequiredWebApplicationContext(sc); ILoginService loginServic=(ILoginService)wac.getBean("loginService"); loginServic.login(); System.out.println("after loginServic.login()"); return new ModelAndView("/helloq", "message", "你好"); } }
更多请见下节:http://www.mark-to-win.com/tutorial/frame_Spring_IOCConfigurationFile.html