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

工作到現(xiàn)在快要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環(huán)境,左轉百度,右轉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>        
        <!-- 數(shù)據(jù)源配置 -->        
        <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類實現(xiàn)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視圖解析器,
    // 保留原有配置
    // 加入自定義參數(shù) 如${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返回數(shù)據(jù)
    @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需要的數(shù)據(jù)源等
/**
 * 定義掃描的根路徑,數(shù)據(jù)源
 * 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類實現(xiàn)thymeleaf中使用到的自定義參數(shù),這個配置寫在WebMvcConfig中
/**
 * 配置thymeleaf自定義參數(shù)的相關方法
 * Created by sam on 16/5/26.
 */
public class SpringUtils {

    // 可以在html中使用${e.res('/')}
    // 將會自動代理到相關靜態(tài)資源下面
    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>
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市辜贵,隨后出現(xiàn)的幾起案子煌恢,更是在濱河造成了極大的恐慌,老刑警劉巖宠页,帶你破解...
    沈念sama閱讀 207,248評論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件左胞,死亡現(xiàn)場離奇詭異,居然都是意外死亡举户,警方通過查閱死者的電腦和手機烤宙,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,681評論 2 381
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來俭嘁,“玉大人门烂,你說我怎么就攤上這事⌒忠” “怎么了屯远?”我有些...
    開封第一講書人閱讀 153,443評論 0 344
  • 文/不壞的土叔 我叫張陵,是天一觀的道長捕虽。 經(jīng)常有香客問我慨丐,道長,這世上最難降的妖魔是什么泄私? 我笑而不...
    開封第一講書人閱讀 55,475評論 1 279
  • 正文 為了忘掉前任房揭,我火速辦了婚禮,結果婚禮上晌端,老公的妹妹穿的比我還像新娘捅暴。我一直安慰自己,他們只是感情好咧纠,可當我...
    茶點故事閱讀 64,458評論 5 374
  • 文/花漫 我一把揭開白布蓬痒。 她就那樣靜靜地躺著,像睡著了一般漆羔。 火紅的嫁衣襯著肌膚如雪梧奢。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 49,185評論 1 284
  • 那天演痒,我揣著相機與錄音亲轨,去河邊找鬼。 笑死鸟顺,一個胖子當著我的面吹牛惦蚊,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 38,451評論 3 401
  • 文/蒼蘭香墨 我猛地睜開眼蹦锋,長吁一口氣:“原來是場噩夢啊……” “哼曾撤!你這毒婦竟也來了?” 一聲冷哼從身側響起晕粪,我...
    開封第一講書人閱讀 37,112評論 0 261
  • 序言:老撾萬榮一對情侶失蹤挤悉,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后巫湘,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體装悲,經(jīng)...
    沈念sama閱讀 43,609評論 1 300
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 36,083評論 2 325
  • 正文 我和宋清朗相戀三年尚氛,在試婚紗的時候發(fā)現(xiàn)自己被綠了诀诊。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 38,163評論 1 334
  • 序言:一個原本活蹦亂跳的男人離奇死亡阅嘶,死狀恐怖属瓣,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情讯柔,我是刑警寧澤抡蛙,帶...
    沈念sama閱讀 33,803評論 4 323
  • 正文 年R本政府宣布,位于F島的核電站魂迄,受9級特大地震影響粗截,放射性物質發(fā)生泄漏。R本人自食惡果不足惜捣炬,卻給世界環(huán)境...
    茶點故事閱讀 39,357評論 3 307
  • 文/蒙蒙 一熊昌、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧湿酸,春花似錦婿屹、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,357評論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至美莫,卻和暖如春页眯,著一層夾襖步出監(jiān)牢的瞬間梯捕,已是汗流浹背厢呵。 一陣腳步聲響...
    開封第一講書人閱讀 31,590評論 1 261
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留傀顾,地道東北人襟铭。 一個月前我還...
    沈念sama閱讀 45,636評論 2 355
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親寒砖。 傳聞我的和親對象是個殘疾皇子赐劣,可洞房花燭夜當晚...
    茶點故事閱讀 42,925評論 2 344

推薦閱讀更多精彩內容