JAVA-第十部分-Spring-集成Junit和web

224 阅读1分钟

写在前面

Spring集成Junit

//通过spring管理junit
@RunWith(SpringJUnit4ClassRunner.class)
//通过xml文件
//@ContextConfiguration("classpath:applicationContext.xml")
//通过全注解
@ContextConfiguration(classes = {SpringConfiguration.class, UserServiceConfiguration.class})
public class SpringJuintTest {

    @Autowired
    private UserService userService;

    @Autowired
    private DataSource dataSource;

    @Test
    public void test() {
        userService.save();
    }

    @Test
    public void test1() throws SQLException {
        System.out.println(dataSource.getConnection());
    }
}

Spring集成web

  • 加载慢用 archetypeCatalog=internal
  • 监听器调用服务类
public class ContextLoaderListener implements ServletContextListener {
    //web启动就会自动调用
    public void contextInitialized(ServletContextEvent sce) {
        AnnotationConfigApplicationContext app = new AnnotationConfigApplicationContext(UserConfiguration.class);
        //将应用上下文存取到最大的域
        ServletContext servletContext = sce.getServletContext();
        servletContext.setAttribute("app",app);
    }
    public void contextDestroyed(ServletContextEvent sce) {
    }
}
//web.xml配置监听器
<!--配置监听器-->
<listener>
  <listener-class>com.java.listener.ContextLoaderListener</listener-class>
</listener>
  • 解除监听器和配置文件的耦合
//读取web.xml的全局参数
ServletContext servletContext = sce.getServletContext();
String contextConfigLocation = servletContext.getInitParameter("contextConfigLocation");
AnnotationConfigApplicationContext app = null;
try {
    app = new AnnotationConfigApplicationContext(Class.forName(contextConfigLocation));
} catch (ClassNotFoundException e) {
    e.printStackTrace();
}

<!--全局初始化参数-->
<context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>com.java.UserConfiguration</param-value>
</context-param>
  • 通过自定义工具类获取应用上下文
public static ApplicationContext getWebApplicationContext(ServletContext servletContext) {
    return (ApplicationContext) servletContext.getAttribute("app");
}

Spring监听器

  • web.xml配置监听器
  • 使用spring内部的监听器和上下文工具类
  • 配置
<!--全局初始化参数-->
<context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!--配置监听器-->
<listener>
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
  • Servlet调用
ServletContext servletContext = this.getServletContext();
//使用spring的工具类获取
ApplicationContext app = WebApplicationContextUtils.getWebApplicationContext(servletContext);
UserService bean = app.getBean(UserService.class);
bean.save();