事务06-事务案例-转账:Spring整合Junit(Spring 笔记016)

这篇博客详细介绍了如何将Spring与JUnit结合进行单元测试,以及如何在Java Web环境中集成Spring,通过ContextLoaderListener加载配置文件。文章还展示了如何在Servlet中调用服务层方法,并提供了在JSP页面中链接Servlet的示例。最后,讲解了Servlet的初始化过程和web.xml中的配置。

导入.jar{核心与依赖:4+1spring−tesr−3.2.0.RELEASE.jar \mathrm{导入}.jar\left\{\begin{array}{l}\mathrm{核心与依赖}:4+1\\spring-tesr-3.2.0.RELEASE.jar\end{array}\right. .jar{4+1springtesr3.2.0.RELEASE.jar
使用Junit xmlpath="applicationContext.xml"并放在src下
并且

String  xmlpath="applicationContext.xml"
ApplicationContext applicationContext= new ClassPathXmlApplicationContext(xmlpath);
UserSersvice userSvice =(UserSvice)applicationContext.getBean(" 实现类的id");

都可由Junit实现

import org.junit.Test;  
import org.junit.runner.RunWith;  
import org.springframework.beans.factory.annotation.Autowired;  
import org.springframework.test.context.ContextConfiguration;  
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;  

  
@RunWith(SpringJUnit4ClassRunner.class)  
@ContextConfiguration(locations = { "classpath:applicationContext.xml" })  
public class JTest {  
    @Autowired  //自动注入
    private AccountService accountService;  
  
    @Test  
    public void demo() {  
        accountService.transfer("jack","rose",1000)
    }  
}  

整合WEB

spring-web-3.2.0.RELEASE.jar
将accountService.transfer(“jack”,“rose”,1000);放到Servlet中
1.tomcat启动时加载配置文件
2.
javaWEB三大核心技术{servlet      init(ServletConfig)→load−on−startupfliter            init(FilterConfig)→web.xml中注册即可listener    SerletContextListener→servletContext对象 \begin{array}{c}javaWEB\\\mathrm{三大}\\\mathrm{核心技术}\end{array}\left\{\begin{array}{l}servlet\;\;\;init(ServletConfig)\rightarrow load-on-startup\\fliter\;\;\;\;\;\;init(FilterConfig)\rightarrow web.xml\mathrm{中注册即可}\\listener\;\;SerletContextListener\rightarrow servletContext\mathrm{对象}\end{array}\right. javaWEBservletinit(ServletConfig)loadonstartupfliterinit(FilterConfig)web.xmllistenerSerletContextListenerservletContext
Spring提供ContextLoaderListener在web.xml中配置监听器

<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param><!--不配置默认在/WEB-INF/applicationContext.xml-->

3.新建jsp

<a herf=${pageContext.request.contextPath}/helloServler>spring容器获得</a>

4.servletde doGet:

//从application作用域(ServletContext)获得Spring容器
ApplicationContext applicationContext =(ApplicationContext)this.getServletContext().getAttribute(WebApplicationContext.RooT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
//操作
AccountService accountService=(AccountService)applicationContext.getBean("accountService");
accountService.transfer("jack","rose",1000);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值