技术程序员寒哥管理的技术专题

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

2016-05-30  本文已影响3209人  MacSam

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

<?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>
/**
 * 继承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配置,如不同的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());
    }
}
/**
 * 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;
    }
}
/**
 * 注册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");
    }
}
/**
 * 定义扫描的根路径,数据源
 * 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;
    }
}
/**
 * 配置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();
    }
}
/** 
  * 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";
    }
}
<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>
/**
 * 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);
}
/**
 * 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;
}
<?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>
上一篇下一篇

猜你喜欢

热点阅读