导入.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+1spring−tesr−3.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.
javaWEB三大核心技术⎩⎨⎧servletinit(ServletConfig)→load−on−startupfliterinit(FilterConfig)→web.xml中注册即可listenerSerletContextListener→servletContext对象
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);
这篇博客详细介绍了如何将Spring与JUnit结合进行单元测试,以及如何在Java Web环境中集成Spring,通过ContextLoaderListener加载配置文件。文章还展示了如何在Servlet中调用服务层方法,并提供了在JSP页面中链接Servlet的示例。最后,讲解了Servlet的初始化过程和web.xml中的配置。
1683

被折叠的 条评论
为什么被折叠?



