spring中通过配置文件注入的方法

2.通过配置文件注入的方法

马 克-to-win:上面的注入方法是通过@Service的注解方法。类似的还有@Repository、@Component、 @Controller,功能大体一样,就是实例化以后放到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();

版权保护,原文出处:http://www.mark-to-win.com/index.html?conthttp://www.mark-to-win.com/index.html?content=Frame/frameUrl.html&chapter=Frame/Spring_web.html#IOCConfigurationFile

猜你喜欢

转载自blog.csdn.net/mark_to_win/article/details/88695929