整合一个基于java config的spring,mybatis和thymeleaf

工作到现在快要1年半了,一直没有时间自己从头搭建个框架,这个周末实在是无聊,真的不想打lol了,(黑色玫瑰开黑的喊我!),正好把之前埋下的坑填完.
你需要以下工具:
IDE : Intellij idea15
jdk : 1.7.0_59
maven : 3.2.2
tomcat : 7.0.54

  • new an empty project,相当于eclipse中的workspace


    Paste_Image.png
  • new a maven module,相当于eclipse中的project,选择maven后一路next,设置自己的名称即可.


    Paste_Image.png
  • 在idea中配置maven,在preferences中将maven_home指向本地的安装路径即可.至于怎么配置maven_home环境,左转百度,右转google


    Paste_Image.png
  • 下面放上一张搭建好的工程结构图


    Paste_Image.png
  • 以下是所有使用的到的jar包依赖. (pom.xml)
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"         
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"         
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">    
<modelVersion>4.0.0</modelVersion>    
<groupId>com.sam</groupId>    
<artifactId>spring-mybatis</artifactId>    
<version>1.0-SNAPSHOT</version>    
<packaging>war</packaging>    
<properties>        
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>        
      <spring.version>4.1.6.RELEASE</spring.version>                  
      <cxf.version>2.7.15</cxf.version>        
      <aspectj.version>1.6.8</aspectj.version>        
      <slf4j-version>1.7.12</slf4j-version>
      <thymeleaf.version>2.1.3.RELEASE</thymeleaf.version>        
      <thymeleaf-layout.version>1.2.5</thymeleaf-layout.version>        
      <log4j-version>1.2.17</log4j-version>        
      <mybatis-version>3.3.0</mybatis-version>        
      <mybatis-spring-version>1.2.3</mybatis-spring-version> 
      <jackson.version>2.4.3</jackson.version>
      <json.version>1.9.13</json.version>            
      <diamond.version>0.0.18</diamond.version>    </properties>    
<dependencies>       
       <!-- 日志配置-->        
       <dependency>            
            <groupId>ch.qos.logback</groupId>   
            <artifactId>logback-classic</artifactId>      
            <version>1.0.13</version>        
       </dependency>        
       <dependency>            
            <groupId>org.slf4j</groupId> 
            <artifactId>slf4j-api</artifactId>    
            <version>${slf4j-version}</version>               
       </dependency>        
       <dependency>            
            <groupId>javax.servlet</groupId>           
            <artifactId>javax.servlet-api</artifactId>     
            <version>3.1.0</version>        
       </dependency>        
       <dependency>                   
            <groupId>org.apache.commons</groupId>            
            <artifactId>commons-lang3</artifactId>                
            <version>3.3</version>        
       </dependency>        
       <dependency>         
            <groupId>com.alibaba</groupId>     
            <artifactId>fastjson</artifactId>      
            <version>1.2.1</version>      
        </dependency>        
        <!-- 数据源配置 -->        
        <dependency>            
             <groupId>commons-dbcp</groupId>     
             <artifactId>commons-dbcp</artifactId>      
             <version>1.4</version>        
        </dependency>        
        <!--mysql-->        
        <dependency>            
             <groupId>mysql</groupId>          
             <artifactId>mysql-connector-java</artifactId>    
             <version>5.1.37</version>     
        </dependency>        
        <dependency>            
             <groupId>org.mybatis</groupId>   
             <artifactId>mybatis-spring</artifactId>           
             <version>${mybatis-spring-version}</version>  
        </dependency>        
        <dependency>            
             <groupId>org.mybatis</groupId>    
             <artifactId>mybatis</artifactId>       
             <version>${mybatis-version}</version>     
         </dependency>        
         <dependency> 
             <groupId>org.mybatis.generator</groupId>         
             <artifactId>mybatis-generator-core</artifactId>      
             <version>1.3.2</version>          
         </dependency>        
         <!-- spring用到的包 -->        
         <dependency>          
             <groupId>org.springframework</groupId>     
             <artifactId>spring-web</artifactId>            
             <version>${spring.version}</version>     
         </dependency>        
         <dependency>     
             <groupId>org.springframework</groupId> 
             <artifactId>spring-core</artifactId>            
             <version>${spring.version}</version>        
         </dependency>        
         <dependency>        
             <groupId>org.springframework</groupId>     
             <artifactId>spring-context</artifactId>            
             <version>4.1.1.RELEASE</version>  
         </dependency>        
         <dependency>            
             <groupId>org.springframework</groupId>          
             <artifactId>spring-beans</artifactId>            
             <version>${spring.version}</version>        
         </dependency>        
         <dependency>         
             <groupId>org.springframework</groupId>    
             <artifactId>spring-aop</artifactId>            
             <version>${spring.version}</version>        
         </dependency>        
         <dependency>          
             <groupId>org.springframework</groupId>         
             <artifactId>spring-jdbc</artifactId>            
             <version>${spring.version}</version>        
         </dependency>       
         <dependency>         
             <groupId>org.springframework</groupId>    
             <artifactId>spring-webmvc</artifactId>    
             <version>${spring.version}</version>       
         </dependency>        
         <dependency>          
             <groupId>org.springframework</groupId>         
             <artifactId>spring-tx</artifactId>            
             <version>${spring.version}</version>        
         </dependency>        
          <!--测试-->        
         <dependency>         
             <groupId>junit</groupId>    
             <artifactId>junit</artifactId>       
             <version>4.11</version>   
             <scope>test</scope>        
         </dependency>        
         <dependency>         
             <groupId>org.springframework</groupId>   
             <artifactId>spring-test</artifactId>            
             <version>4.1.1.RELEASE</version>          
             <scope>test</scope>     
         </dependency>        
         <dependency>       
             <groupId>javax</groupId>            
             <artifactId>javaee-api</artifactId>   
             <version>7.0</version>       
             <scope>provided</scope>       
         </dependency>        
         <!-- thymeleaf -->   
         <dependency>            
             <groupId>org.thymeleaf</groupId>      
             <artifactId>thymeleaf-spring4</artifactId>    
             <version>${thymeleaf.version}</version>   
             <exclusions>     
                  <exclusion>              
                  <groupId>org.slf4j</groupId>     
                  <artifactId>slf4j-api</artifactId>     
                  </exclusion>            
             </exclusions>        
         </dependency>        
         <dependency>           
             <groupId>nz.net.ultraq.thymeleaf</groupId>          
             <artifactId>thymeleaf-layout-dialect</artifactId> 
             <version>${thymeleaf-layout.version}</version>   
         </dependency>       
        <!--diamond-->     
        <dependency>      
              <groupId>com.github.bingoohuang</groupId>     
              <artifactId>diamond-sdk</artifactId>            
              <version>0.0.5</version>
        </dependency>        
        <dependency>         
              <groupId>com.github.bingoohuang</groupId>     
              <artifactId>diamond-client</artifactId>           
              <version>${diamond.version}</version>    
        </dependency>     
        <dependency>         
              <groupId>org.aspectj</groupId>  
              <artifactId>aspectjrt</artifactId>  
              <version>${aspectj.version}</version>     
       </dependency>        
       <dependency>           
            <groupId>org.aspectj</groupId>      
            <artifactId>aspectjweaver</artifactId>   
            <version>${aspectj.version}</version>   
       </dependency>        
       <!--jackson-->       
       <dependency>     
            <groupId>org.codehaus.jackson</groupId>     
            <artifactId>jackson-mapper-asl</artifactId>    
            <version>${json.version}</version>        
       </dependency>        
       <dependency>
          
            <groupId>org.codehaus.jackson</groupId>
   
            <artifactId>jackson-core-asl</artifactId>
 
            <version>${json.version}</version>

       </dependency>
       <dependency>          
            <groupId>com.fasterxml.jackson.core</groupId>          
            <artifactId>jackson-databind</artifactId>        
            <version>${jackson.version}</version>
      </dependency>
      <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
        </dependency>
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3</version>
        </dependency>
        <dependency>
            <groupId>commons-collections</groupId>
            <artifactId>commons-collections</artifactId>
            <version>3.2.1</version>
        </dependency>
    </dependencies>
        <build>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.3.2</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>
  • 定义一个WebMvcConfig类实现WebMvcConfigurerAdapter
/**
 * 继承web mvc adapter
 * 包含通用的配置
 * Created by sam on 16/5/26.
 */
public class WebMvcConfig extends WebMvcConfigurerAdapter {
    
    //static resources
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/css/**").addResourceLocations("/css/");
        registry.addResourceHandler("/img/**").addResourceLocations("/img/");
        registry.addResourceHandler("/js/**").addResourceLocations("/js/");
    }
                                                                                                          
    // 配置thymeleaf视图解析器,
    // 保留原有配置
    // 加入自定义参数 如${e.res()}
    @Bean
    public ThymeleafViewResolver thymeleafViewResolver() {
        ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
        viewResolver.setTemplateEngine(templateEngine());
        viewResolver.setCharacterEncoding("UTF-8");

        Map<String, Object> oldStaticVariables = viewResolver.getStaticVariables();
        Map<String, Object> staticVariables = Maps.newHashMap(oldStaticVariables);
        staticVariables.put("e", new SpringUtils());
        viewResolver.setStaticVariables(staticVariables);
        return viewResolver;
    }
                                                                                                            
    //配置模板引擎
    @Bean
    public SpringTemplateEngine templateEngine() {
        SpringTemplateEngine engine = new SpringTemplateEngine();
        engine.setTemplateResolver(templateResolver());
        engine.addDialect(new LayoutDialect());
        return engine;
    }
    
    //配置模板解析器
    @Bean
    public TemplateResolver templateResolver() {
        ClassLoaderTemplateResolver templateResolver;
        templateResolver = new ClassLoaderTemplateResolver();
        templateResolver.setTemplateMode("XHTML");
        templateResolver.setPrefix("views/");
        templateResolver.setCharacterEncoding("UTF-8");
        templateResolver.setSuffix(".html");
        templateResolver.setCacheable(false); // true by default
        return templateResolver;
    }

    //定义spring文件上传编码
    @Bean
    public CommonsMultipartResolver multipartResolver() {
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
        multipartResolver.setDefaultEncoding("UTF-8");
        return multipartResolver;
    }

    //解析json返回数据
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
        List<MediaType> mediaTypes = new ArrayList(converter.getSupportedMediaTypes());
        converter.setSupportedMediaTypes(mediaTypes);
        mediaTypes.addAll(asList(MediaType.TEXT_PLAIN, MediaType.TEXT_HTML, MediaType.TEXT_XML));
        converters.add(converter);
    }
    
    //配置diamond,如果本地没有配置diamond可以注释该段代码
    @Bean
    public DiamondSDK diamondSDK() {
        Minerable minerable = new Miner().getMiner("poet.diamond", "diamondConfig");
        DiamondSDK diamondSDK = new DiamondSDK(
                new DiamondSDKConf(
                        Lists.newArrayList(new DiamondConf(
                                minerable.getString("diamondIp"),
                                minerable.getInt("diamondPort"),
                                minerable.getString("diamondUsername"),
                                minerable.getString("diamondPassword")))));
        return diamondSDK;
    }
    
    //快捷定义ViewController
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
    }
}
  • 定义实际使用到的spring mvc config
/**
 * 实际使用到的配置文件
 * 可以将该文件放入不同的工程来辨别使用不同的spring配置,如不同的interceptor
 * Created by sam on 16/5/26.
 */
@EnableWebMvc
@Configuration
@EnableAspectJAutoProxy
public class SpringMvcConfig extends WebMvcConfig {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new SpringInterceptor());
    }
}
  • 以下是上面配置中使用到的interceptor
/**
 * Created by sam on 16/5/26.
 */
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
@Component
public class SpringInterceptor extends HandlerInterceptorAdapter {

    private Logger logger = LoggerFactory.getLogger(SpringInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        logger.debug("interceptor works --------- return true");
        return true;
    }
}
  • 注册DispatcherServlet
/**
 * 注册Spring DispatcherServlet
 * Created by sam on 16/5/26.
 */
public class SpringMvcInitializer extends AbstractAnnotationConfigDispatcherServletInitializer{

    //配置扫描根路径
    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class[]{RootConfig.class};
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class<?>[]{};
    }

    @Override
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }

    @Override
    protected Filter[] getServletFilters() {
        CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
        characterEncodingFilter.setEncoding("UTF-8");
        characterEncodingFilter.setForceEncoding(true);
        return new Filter[]{characterEncodingFilter};
    }

    @Override
    protected void customizeRegistration(ServletRegistration.Dynamic registration) {
       registration.setInitParameter("throwExceptionIfNoHandlerFound", "true");
    }
}
  • 配置上面配置中的RootConfig,包括配置包的扫描路径,配置mybatis需要的数据源等
/**
 * 定义扫描的根路径,数据源
 * Created by sam on 16/5/26.
 */
@Configuration
@ComponentScan(basePackages = "com.sam")
@MapperScan(basePackages = "com.sam")
public class RootConfig {

    private static String diver = "com.mysql.jdbc.Driver";

    private static String url = "jdbc:mysql://localhost:3306/YOUR_INSTANCE_NAME";

    private static String user = "YOUR_NAME";

    private static String pwd = "YOUR_PASSWORD";

    @Bean
    public BasicDataSource dataSource() {
        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setDriverClassName(diver);
        dataSource.setUrl(url);
        dataSource.setUsername(user);
        dataSource.setPassword(pwd);
        return dataSource;
    }

    @Bean
    public DataSourceTransactionManager dataSourceTransactionManager() throws NamingException {
        return new DataSourceTransactionManager(dataSource());
    }

    @Bean
    public SqlSessionFactoryBean sqlSessionFactory(ApplicationContext ap) throws Exception {
        SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource());
        sessionFactory.setTypeAliasesPackage("com.sam");
        return sessionFactory;
    }
}
  • 定义SpringUtils类实现thymeleaf中使用到的自定义参数,这个配置写在WebMvcConfig中
/**
 * 配置thymeleaf自定义参数的相关方法
 * Created by sam on 16/5/26.
 */
public class SpringUtils {

    // 可以在html中使用${e.res('/')}
    // 将会自动代理到相关静态资源下面
    public static String res(String relativeResPath) {
        Minerable resConfig = new Miner().getMiner("poet.base", "res");

        String resVersion = resConfig.getString("version", "1");
        String baseResPath = resConfig.getString("prefix");
        if (baseResPath == null) throw new RuntimeException("prefix config is NULL.");

        return new StringBuilder(removeEnd(baseResPath, "/")).append("/").append(removeStart(relativeResPath, "/")).append("?v=").append(resVersion).toString();
    }
}
  • 定义helloWorldController来测试下
/** 
  * Created by sam on 16/5/26. 
  */
@Controller
@RequestMapping("/hello")
public class HelloWorldController {

    @Autowired
    UserDao userDao;

    private Logger logger = LoggerFactory.getLogger(HelloWorldController.class);

    @RequestMapping("/world")
    public String hello(Model model) {
        String email = "sam@balabala.com";
        String name = userDao.queryUserNameByEmail(email);
        User user = userDao.queryUserInfoByEmail(email);

        logger.debug("you have been here !");
        model.addAttribute("hello", "您好! " + name);
        model.addAttribute("world", "everything is " + user.getUserId());
        return "sam";
    }

    @RequestMapping("/test")
    public String test(Model model){
        logger.debug(">>>>>>>>我就测试下日志 debug  <<<<<<<<<");
        logger.info(">>>>>>>> 我就测试下日志 info   <<<<<<<<<");
        model.addAttribute("hello", "您好! test");
        model.addAttribute("world", "everything is id");
        return "sam";
    }
}
  • 在resources下建views夹子,sam.html如下
<html lang="en">
<head>
    <meta charset="UTF-8"/>
    <title>my first html</title>
</head>
<body>
<h1 data-th-text="${hello}"></h1>
<h1 data-th-text="${world}"></h1>
</body>
</html>
  • UserDao
/**
 * Created by sam on 16/5/29.
 */
@Service
public interface UserDao {

    @Select("select customer_name from customer where email= #{email}")
    String queryUserNameByEmail(@Param("email") String email);

    User queryUserInfoByEmail(@Param("email") String email);
}
  • User
/**
 * Created by sam on 16/5/29.
 */
public class User {

    private String userId;

    private String userName;

    private String email;

    //get set toString and so on;
}
  • 在你的MySQL中建一个Customer表(customer_id,customer_name,email)即可
  • 在resources下建立与dao相同包名的xml文件,在你的MySQL中建一个Customer表,包含customer_id,customer_name,email即可,
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.sam.dao.UserDao">
    <resultMap id="User" type="com.sam.domain.User">
        <id column="customer_id" property="userId" jdbcType="VARCHAR"/>
        <result column="customer_name" property="userName" jdbcType="VARCHAR"/>
        <result column="email" property="email" jdbcType="VARCHAR"/>
    </resultMap>

    <select id="queryUserInfoByEmail" resultMap="User" parameterType="java.lang.String">
        select customer_id,customer_name,email
        from customer
        where email= #{email,jdbcType=VARCHAR}
    </select>
</mapper>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 206,968评论 6 482
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 88,601评论 2 382
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 153,220评论 0 344
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 55,416评论 1 279
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 64,425评论 5 374
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,144评论 1 285
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,432评论 3 401
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,088评论 0 261
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 43,586评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,028评论 2 325
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,137评论 1 334
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,783评论 4 324
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,343评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,333评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,559评论 1 262
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,595评论 2 355
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,901评论 2 345

推荐阅读更多精彩内容