要点:

  1. 配置继承WebApplicationInitializer的类作为启动类,相当于配置web.xml文件
  2. 使用@Configuration注解一个类,在类中的方式使用@Bean注解,则表名该方法的返回值为一个Bean,相应于配置applicationContext.xml等spring的xml配置文件

配置启动类

继承WebApplicationInitializer并重新onStartup方法,加载配置类,相当于配置web.xml文件

 public class WebAppInitConfig implements WebApplicationInitializer {

     @Override
public void onStartup(ServletContext container) throws ServletException {
// Create the 'root' Spring application context
AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
rootContext.register(RootConfig.class);//这是自定义的配置类,这个配置类会影响项目全局 // Manage the lifecycle of the root application context
container.addListener(new ContextLoaderListener(rootContext)); // Create the dispatcher servlet's Spring application context
AnnotationConfigWebApplicationContext dispatcherContext = new AnnotationConfigWebApplicationContext();
dispatcherContext.register(WebMvcConfig.class);//这是自定义的配置类,这个配置类只会影响当前模块 // Register and map the dispatcher servlet
ServletRegistration.Dynamic dispatcher = container.addServlet("dispatcher", new DispatcherServlet(dispatcherContext));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
}
}

AnnotationConfigApplicationContext:用来把使用注解的配置类加载到spring容器中,也就是把那些在配置类中定义的bean交给spring管理

也可以使用WebApplicationInitializer的实现类AbstractDispatcherServletInitializerAbstractAnnotationConfigDispatcherServletInitializer来进行更为简洁的配置,官方文档地址,只要实现了WebApplicationInitializer将会被servlet容器自动识别并加载

使用AbstractAnnotationConfigDispatcherServletInitializer配置示例如下

 public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

     @Override
protected Class<?>[] getRootConfigClasses() {
return new Class[]{RootConfig.class};
} @Override
protected Class<?>[] getServletConfigClasses() {
return new Class[]{WebMvcConfig.class};;
} @Override
protected String[] getServletMappings() {
return new String[]{"/"};
} }

自定义配置类

配置spring管理bean,相应于配置applicationContext.xml等spring的xml配置文件,就是上面使用WebApplicationInitializer加载的类

 @Configuration
@EnableWebMvc //注解驱动springMVC 相当于xml中的<mvc:annotation-driven>
@ComponentScan(basePackages = "com.woncode") //启用组件扫描
public class WebMvcConfig extends WebMvcConfigurerAdapter {
//配置静态资源的处理,要求DispatchServlet对静态资源的请求转发到servlet容器中默认的Servlet上
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
} @Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/statics/**").addResourceLocations("/WEB-INF/classes/statics/");
super.addResourceHandlers(registry);
} @Bean
public InternalResourceViewResolver viewResolver(){
InternalResourceViewResolver resolver= new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/classes/templates/");
resolver.setSuffix(".html");
resolver.setExposeContextBeansAsAttributes(true);
return resolver;
} }

@Import注解:用来引入其他配置类到当前配置类,然后就可以在当前配置类中使用其他配置类中的bean了,这在分模块的项目中很有用,因为分模块就是希望分割配置,但是有时又需要使用一些其他已经定义过的配置类,所以可以用此导入

集成JUnit单元测试

添加sprig-test的maven依赖

在测试类头上加如下注解,其中配置类HibernateConfig参考另一篇博文《基于Java配置Spring加Hibernate和再加SpringData时的差别》,是配置使用Spring+hibernate的

 @Transactional
@WebAppConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {WebMvcConfig.class, HibernateConfig.class})
public class SpringTest {
}

注意:

  1. 如果使用Spring MVC则一定要加@WebAppConfiguration注解,否则无法载入web上下文环境,我在这个坑好久
  2. 在测试方法中如果进行一些数据库事物操作,比如要测试插入数据的方法,因为Spring测试套件在测试事务方法执行完成后会自动回滚,如果想要插入的数据持久保存到数据库中,则要在测试方法头上加@Rollback(false)注解

Spring完全基于Java配置和集成Junit单元测试的更多相关文章

  1. Spring Security基于Java配置

    Maven依赖 <dependencies> <!-- ... other dependency elements ... --> <dependency> < ...

  2. spring-security-4 (2)spring security 基于Java配置的搭建

    一.spring security的模块 搭建spring security首先我们要导入必须的jar,即maven的依赖.spring security按模块划分,一个模块对应一个jar. spri ...

  3. spring实战六之使用基于java配置的Spring

    之前接触的都是基于XML配置的Spring,Spring3.0开始可以几乎不使用XML而使用纯粹的java代码来配置Spring应用.使用基于java配置的Spring的步骤如下: 1. 创建基于ja ...

  4. Spring入门(8)-基于Java配置而不是XML

    Spring入门(8)-基于Java配置而不是XML 本文介绍如何应用Java配置而不是通过XML配置Spring. 0. 目录 声明一个简单Bean 声明一个复杂Bean 1. 声明一个简单Bean ...

  5. springmvc基于java配置的实现

    该案例的github地址:https://github.com/zhouyanger/demo/tree/master/springmvc-noxml-demo 1.介绍 之前搭建SpringMvc项 ...

  6. Spring IoC — 基于Java类的配置

    普通的POJO只要标注@Configuration注解,就可以为Spring容器提供Bean定义的信息了,每个标注了@Bean的类方法都相当于提供一个Bean的定义信息. 基于Java类的配置方法和基 ...

  7. Spring(八)之基于Java配置

    基于 Java 的配置 到目前为止,你已经看到如何使用 XML 配置文件来配置 Spring bean.如果你熟悉使用 XML 配置,那么我会说,不需要再学习如何进行基于 Java 的配置是,因为你要 ...

  8. 【Spring】28、Spring中基于Java的配置@Configuration和@Bean用法.代替xml配置文件

    Spring中为了减少xml中配置,可以生命一个配置类(例如SpringConfig)来对bean进行配置. 一.首先,需要xml中进行少量的配置来启动Java配置: <?xml version ...

  9. Spring中基于Java的配置@Configuration和@Bean用法

    spring中为了减少xml中配置,可以声明一个配置类(例如SpringConfig)来对bean进行配置. 一.首先,需要xml中进行少量的配置来启动Java配置: <?xml version ...

随机推荐

  1. property()函数

    class C: def __init__(self, size=10): self.size = size def getXSize(self): return self.size def setX ...

  2. jQuery系列 第二章 jQuery框架使用准备

    第二章 jQuery框架使用准备 2.1 jQuery框架和JavaScript加载模式对比 jQuery框架的加载模式 <script> window.onload = function ...

  3. 使用Git简单笔记

    这里只是作为简单的笔记整理,第一次使用的推荐先看一下廖大的教程,内容很多很细,可以边看边练.看不懂的地方先记着.争取七七八八看下来. ================================= ...

  4. 网络流入门-POJ1459PowerNetwork-Dinic模板

    (我有什么错误或者你有什么意见,欢迎留言或私聊!谢谢!) (Ps:以前听说过网络流,想着以后再学,这次中南多校赛也碰到有关网络流的题目,想着这两天试着学学这个吧~~ 这是本人网络流入门第二题,不知道怎 ...

  5. [C#].Net Core 获取 HttpContext.Current 以及 AsyncLocal 与 ThreadLocal

    在 DotNetCore 当中不再像 MVC5 那样可以通过 HttpContext.Current 来获取到当前请求的上下文. 不过微软提供了一个 IHttpContextAccessor 来让我们 ...

  6. [LeetCode] Design Compressed String Iterator 设计压缩字符串的迭代器

    Design and implement a data structure for a compressed string iterator. It should support the follow ...

  7. [LeetCode] Find Bottom Left Tree Value 寻找最左下树结点的值

    Given a binary tree, find the leftmost value in the last row of the tree. Example 1: Input: 2 / \ 1 ...

  8. UVA 11584 划分回文字串

    将其划分为尽可能少的回文串 dp[i] = min(dp[i],dp[j] + 1)    来表示j+1~i是回文串 #include <iostream> #include <cs ...

  9. uva 10118(DP)

    UVA 10118 题意: 有4堆糖果,每堆有n(最多40)个,有一个篮子,最多装5个糖果,我们每次只能从某一堆糖果里拿出一个糖果, 如果篮子里有两个相同的糖果,那么就可以把这两个(一对)糖果放进自己 ...

  10. bzoj1492[NOI2007]货币兑换Cash cdq分治+斜率优化dp

    1492: [NOI2007]货币兑换Cash Time Limit: 5 Sec  Memory Limit: 64 MBSubmit: 5541  Solved: 2228[Submit][Sta ...