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", "你好");
}
}
更多内容请见原文,文章转载自:https://blog.csdn.net/qq_44591615/article/details/109206207
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义