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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值