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

导 入 . j a r { 核 心 与 依 赖 : 4 + 1 s p r i n g − t e s r − 3.2.0. R E L E A S E . j a r \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.
j a v a W E B 三 大 核 心 技 术 { s e r v l e t        i n i t ( S e r v l e t C o n f i g ) → l o a d − o n − s t a r t u p f l i t e r              i n i t ( F i l t e r C o n f i g ) → w e b . x m l 中 注 册 即 可 l i s t e n e r      S e r l e t C o n t e x t L i s t e n e r → s e r v l e t C o n t e x t 对 象 \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);

猜你喜欢

转载自blog.csdn.net/ResumeProject/article/details/112958762