├── .gitignore ├── README.md ├── ToDo ├── pom.xml └── src ├── main ├── java │ └── org │ │ └── sandbox │ │ ├── SpringBootMybatisApplication.java │ │ ├── aop │ │ └── AopMonitor.java │ │ ├── config │ │ ├── CustomInterceptor.java │ │ ├── CustomUrlRewriteFilter.java │ │ ├── DaoConfig.java │ │ ├── InterceptorConfig.java │ │ ├── JmsConfig.java │ │ ├── MysqlConfig.java │ │ ├── OAuth2AuthorizationServerConfig.java │ │ ├── OAuth2ResourceServerConfig.java │ │ ├── RedisConfig.java │ │ ├── ShiroConfig.java │ │ ├── SwaggerConfig.java │ │ ├── TaskConfig.java │ │ ├── UrlRewriteConfig.java │ │ └── WebSecurityConfig.java │ │ ├── controller │ │ ├── ArrayParamsController.java │ │ ├── ExampleExceptionController.java │ │ ├── HateoasController.java │ │ ├── JmsController.java │ │ ├── MongoController.java │ │ ├── OAuthController.java │ │ ├── PersonController.java │ │ ├── ProfilesController.java │ │ ├── RedisController.java │ │ └── SecurityController.java │ │ ├── exception │ │ ├── CustomException.java │ │ ├── ErrorDetail.java │ │ ├── ExampleExceptionHandler.java │ │ ├── ValidateObject.java │ │ └── ValidationError.java │ │ ├── hateoas │ │ └── Article.java │ │ ├── mongodb │ │ ├── Customer.java │ │ ├── CustomerRepository.java │ │ ├── CustomerRepositoryCustom.java │ │ └── CustomerRepositoryImpl.java │ │ ├── orm │ │ ├── Person.java │ │ ├── PersonDao.java │ │ ├── PersonExample.java │ │ └── PersonMapper.java │ │ └── service │ │ ├── JmsConsumerService.java │ │ ├── JmsProducerService.java │ │ ├── MongoService.java │ │ ├── OAuthService.java │ │ ├── PersonService.java │ │ ├── RedisService.java │ │ └── SecurityService.java └── resources │ ├── application-dev.properties │ ├── application-pro.properties │ ├── application.properties │ ├── logback.properties │ ├── logback.xml │ ├── messages.properties │ ├── mysql │ ├── PersonMapper.xml │ ├── init.sql │ └── mybatis-generator.xml │ ├── static │ └── swagger-ui │ │ ├── css │ │ ├── reset.css │ │ └── screen.css │ │ ├── images │ │ ├── explorer_icons.png │ │ ├── logo_small.png │ │ ├── pet_store_api.png │ │ ├── throbber.gif │ │ └── wordnik_api.png │ │ ├── index.html │ │ ├── lib │ │ ├── backbone-min.js │ │ ├── handlebars-1.0.0.js │ │ ├── highlight.7.3.pack.js │ │ ├── jquery-1.8.0.min.js │ │ ├── jquery.ba-bbq.min.js │ │ ├── jquery.slideto.min.js │ │ ├── jquery.wiggle.min.js │ │ ├── shred.bundle.js │ │ ├── shred │ │ │ └── content.js │ │ ├── swagger-oauth.js │ │ ├── swagger.js │ │ └── underscore-min.js │ │ ├── o2c.html │ │ ├── swagger-ui.js │ │ └── swagger-ui.min.js │ └── urlrewrite.xml └── test └── java └── org └── sandbox ├── ControllerTest.java ├── PersonServiceMockTest.java ├── PersonStandaloneMockTest.java └── PersonWebApplicationContextTest.java /.gitignore: -------------------------------------------------------------------------------- 1 | .idea 2 | *.iml 3 | target 4 | */target 5 | logs -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | #spring-boot-example 2 | 3 | ##introduction 4 | 5 | This project contains demos about MySQL, MyBatis, logback, url rewrite, interceptor, aop, mongodb, Test Framework(Mock), ActiveMQ, 6 | Security(Basic Authentication, Digest Authentication, OAuth2 Authentication), transaction, Rest Template. 7 | -------------------------------------------------------------------------------- /ToDo: -------------------------------------------------------------------------------- 1 | #logback日志 2 | #url rewrite 3 | #拦截器 4 | #AOP 5 | #mongodb 6 | #test 7 | #mq 8 | #security 9 | #transaction 10 | #task 11 | #exception 12 | #document 13 | #HATEOAS 14 | Shiro 15 | Hadoop -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | org.sandbox.springboot 7 | spring-boot-example 8 | 0.0.1-SNAPSHOT 9 | jar 10 | 11 | spring-boot-example 12 | Spring Boot Example 13 | 14 | 15 | org.springframework.boot 16 | spring-boot-starter-parent 17 | 1.2.5.RELEASE 18 | 19 | 20 | 21 | 22 | UTF-8 23 | 1.8 24 | 1.2.4 25 | 26 | 27 | 28 | 29 | org.springframework.boot 30 | spring-boot-starter-jdbc 31 | 32 | 33 | org.springframework.boot 34 | spring-boot-starter-web 35 | 36 | 37 | org.springframework.boot 38 | spring-boot-starter-redis 39 | 40 | 41 | org.mybatis 42 | mybatis 43 | 3.3.0 44 | 45 | 46 | org.mybatis 47 | mybatis-spring 48 | 1.2.3 49 | 50 | 51 | mysql 52 | mysql-connector-java 53 | 5.1.35 54 | 55 | 56 | c3p0 57 | c3p0 58 | 0.9.1.2 59 | 60 | 61 | org.tuckey 62 | urlrewritefilter 63 | 4.0.3 64 | 65 | 66 | org.springframework.boot 67 | spring-boot-starter-aop 68 | 69 | 70 | org.springframework.boot 71 | spring-boot-starter-data-mongodb 72 | 73 | 74 | org.springframework.boot 75 | spring-boot-starter-test 76 | test 77 | 78 | 79 | com.jayway.jsonpath 80 | json-path-assert 81 | 2.0.0 82 | test 83 | 84 | 85 | javax.inject 86 | javax.inject 87 | 1 88 | 89 | 90 | org.springframework 91 | spring-jms 92 | 93 | 94 | org.apache.activemq 95 | activemq-broker 96 | 97 | 98 | org.apache.activemq 99 | activemq-pool 100 | 5.12.0 101 | 102 | 103 | org.springframework.boot 104 | spring-boot-starter-jta-atomikos 105 | 106 | 107 | org.springframework.boot 108 | spring-boot-starter-security 109 | 110 | 111 | org.springframework.security.oauth 112 | spring-security-oauth2 113 | 2.0.7.RELEASE 114 | 115 | 116 | com.mangofactory 117 | swagger-springmvc 118 | 1.0.2 119 | 120 | 121 | org.springframework.hateoas 122 | spring-hateoas 123 | 0.17.0.RELEASE 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | org.springframework.boot 151 | spring-boot-maven-plugin 152 | 153 | 154 | org.mybatis.generator 155 | mybatis-generator-maven-plugin 156 | 1.3.2 157 | 158 | src/main/resources/mysql/mybatis-generator.xml 159 | true 160 | 161 | 162 | 163 | mysql 164 | mysql-connector-java 165 | 5.1.35 166 | 167 | 168 | 169 | 170 | 171 | 172 | 173 | -------------------------------------------------------------------------------- /src/main/java/org/sandbox/SpringBootMybatisApplication.java: -------------------------------------------------------------------------------- 1 | package org.sandbox; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.boot.builder.SpringApplicationBuilder; 6 | import org.springframework.boot.context.web.SpringBootServletInitializer; 7 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; 8 | import org.springframework.security.core.authority.AuthorityUtils; 9 | import org.springframework.security.core.context.SecurityContextHolder; 10 | 11 | @SpringBootApplication 12 | //extends SpringBootServletInitializer 13 | public class SpringBootMybatisApplication { 14 | 15 | public static void main(String[] args) { 16 | SpringApplication.run(SpringBootMybatisApplication.class, args); 17 | } 18 | 19 | // @Override 20 | // protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { 21 | // // Customize the application or call application.sources(...) to add sources 22 | // 23 | // application.sources(SpringBootMybatisApplication.class); 24 | // return application; 25 | // } 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/org/sandbox/aop/AopMonitor.java: -------------------------------------------------------------------------------- 1 | package org.sandbox.aop; 2 | 3 | import org.aspectj.lang.JoinPoint; 4 | import org.aspectj.lang.annotation.AfterReturning; 5 | import org.aspectj.lang.annotation.Aspect; 6 | import org.springframework.stereotype.Component; 7 | 8 | /** 9 | * Author: zhangxin 10 | * Date: 15-9-1 11 | */ 12 | @Aspect 13 | @Component 14 | public class AopMonitor { 15 | 16 | @AfterReturning("execution(* org.sandbox.service.PersonService.*(..))") 17 | public void afterReturningAdvisor(JoinPoint joinPoint) { 18 | System.out.println("@@@@@Completed: " + joinPoint + "@@@@@"); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/org/sandbox/config/CustomInterceptor.java: -------------------------------------------------------------------------------- 1 | package org.sandbox.config; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; 6 | 7 | import javax.servlet.http.HttpServletRequest; 8 | import javax.servlet.http.HttpServletResponse; 9 | 10 | /** 11 | * Created by zhangxin on 15/8/31. 12 | */ 13 | public class CustomInterceptor extends HandlerInterceptorAdapter { 14 | 15 | private Logger logger = LoggerFactory.getLogger(this.getClass()); 16 | 17 | @Override 18 | public boolean preHandle(HttpServletRequest request, 19 | HttpServletResponse response, Object handler) throws Exception { 20 | logger.info("#####Pre request interceptor ... #####"); 21 | 22 | return true; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/org/sandbox/config/CustomUrlRewriteFilter.java: -------------------------------------------------------------------------------- 1 | package org.sandbox.config; 2 | 3 | import org.tuckey.web.filters.urlrewrite.Conf; 4 | import org.tuckey.web.filters.urlrewrite.UrlRewriteFilter; 5 | import org.tuckey.web.filters.urlrewrite.UrlRewriter; 6 | 7 | import javax.servlet.*; 8 | import java.io.InputStream; 9 | 10 | /** 11 | * Author: zhangxin 12 | * Date: 15-8-29 13 | */ 14 | public class CustomUrlRewriteFilter extends UrlRewriteFilter { 15 | private UrlRewriter urlRewriter; 16 | 17 | @Override 18 | public void loadUrlRewriter(FilterConfig filterConfig) throws ServletException { 19 | try { 20 | InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("urlrewrite.xml"); 21 | Conf conf1 = new Conf(filterConfig.getServletContext(), inputStream, "urlrewrite.xml", ""); 22 | urlRewriter = new UrlRewriter(conf1); 23 | } catch (Exception e) { 24 | throw new ServletException(e); 25 | } 26 | } 27 | 28 | @Override 29 | public UrlRewriter getUrlRewriter(ServletRequest request, ServletResponse response, FilterChain chain) { 30 | return urlRewriter; 31 | } 32 | 33 | @Override 34 | public void destroyUrlRewriter() { 35 | if(urlRewriter != null) 36 | urlRewriter.destroy(); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/org/sandbox/config/DaoConfig.java: -------------------------------------------------------------------------------- 1 | package org.sandbox.config; 2 | 3 | import org.apache.ibatis.session.SqlSessionFactory; 4 | import org.sandbox.orm.PersonDao; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.context.annotation.Bean; 7 | import org.springframework.context.annotation.Configuration; 8 | 9 | /** 10 | * Author: zhangxin 11 | * Date: 15-9-16 12 | */ 13 | @Configuration 14 | public class DaoConfig { 15 | 16 | @Autowired 17 | private SqlSessionFactory sqlSessionFactory; 18 | 19 | @Bean 20 | public PersonDao personDao() { 21 | PersonDao personDao = new PersonDao(); 22 | personDao.setSqlSessionFactory(sqlSessionFactory); 23 | return personDao; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/org/sandbox/config/InterceptorConfig.java: -------------------------------------------------------------------------------- 1 | package org.sandbox.config; 2 | 3 | import org.springframework.context.annotation.Bean; 4 | import org.springframework.context.annotation.Configuration; 5 | import org.springframework.web.servlet.config.annotation.InterceptorRegistry; 6 | import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; 7 | 8 | /** 9 | * Created by zhangxin on 15/8/31. 10 | */ 11 | @Configuration 12 | public class InterceptorConfig extends WebMvcConfigurerAdapter { 13 | 14 | @Bean 15 | public CustomInterceptor interceptor() { 16 | return new CustomInterceptor(); 17 | } 18 | 19 | @Override 20 | public void addInterceptors(InterceptorRegistry registry) { 21 | registry.addInterceptor(interceptor()).addPathPatterns("/demo/v1/**"); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/org/sandbox/config/JmsConfig.java: -------------------------------------------------------------------------------- 1 | package org.sandbox.config; 2 | 3 | import org.apache.activemq.command.ActiveMQQueue; 4 | import org.springframework.context.annotation.Bean; 5 | import org.springframework.context.annotation.Configuration; 6 | import org.springframework.jms.annotation.EnableJms; 7 | 8 | import javax.jms.Queue; 9 | 10 | /** 11 | * Author: zhangxin 12 | * Date: 15-9-7 13 | */ 14 | @Configuration 15 | public class JmsConfig { 16 | 17 | @Bean 18 | public Queue queue() { 19 | return new ActiveMQQueue("sample.queue"); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/org/sandbox/config/MysqlConfig.java: -------------------------------------------------------------------------------- 1 | package org.sandbox.config; 2 | 3 | import com.mchange.v2.c3p0.ComboPooledDataSource; 4 | import org.apache.ibatis.session.SqlSessionFactory; 5 | import org.mybatis.spring.SqlSessionFactoryBean; 6 | import org.mybatis.spring.annotation.MapperScan; 7 | import org.springframework.context.annotation.Bean; 8 | import org.springframework.context.annotation.Configuration; 9 | import org.springframework.core.io.ClassPathResource; 10 | import org.springframework.jdbc.datasource.DataSourceTransactionManager; 11 | 12 | import javax.sql.DataSource; 13 | 14 | /** 15 | * Created by zhangxin on 15/8/26. 16 | */ 17 | 18 | @Configuration 19 | @MapperScan(basePackages = "org.sandbox.orm") 20 | public class MysqlConfig { 21 | @Bean 22 | public DataSource dataSource() throws Exception { 23 | ComboPooledDataSource dataSource = new ComboPooledDataSource(); 24 | 25 | dataSource.setDriverClass("com.mysql.jdbc.Driver"); 26 | dataSource.setJdbcUrl("jdbc:mysql://127.0.0.1:3306/test?autoReconnect=true&useCompression=true" + 27 | "&useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true"); 28 | dataSource.setUser("root"); 29 | dataSource.setPassword("mysql"); 30 | dataSource.setAcquireIncrement(10); 31 | dataSource.setIdleConnectionTestPeriod(60); 32 | dataSource.setMaxPoolSize(100); 33 | dataSource.setMaxStatements(50); 34 | dataSource.setMinPoolSize(10); 35 | 36 | return dataSource; 37 | } 38 | 39 | @Bean 40 | public DataSourceTransactionManager transactionManager() throws Exception { 41 | return new DataSourceTransactionManager(dataSource()); 42 | } 43 | 44 | @Bean 45 | public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception { 46 | final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean(); 47 | sessionFactory.setDataSource(dataSource); 48 | sessionFactory.setMapperLocations(new ClassPathResource[] {new ClassPathResource("mysql/PersonMapper.xml")}); 49 | return sessionFactory.getObject(); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/main/java/org/sandbox/config/OAuth2AuthorizationServerConfig.java: -------------------------------------------------------------------------------- 1 | package org.sandbox.config; 2 | 3 | import org.springframework.context.annotation.Configuration; 4 | import org.springframework.security.authentication.AuthenticationManager; 5 | import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer; 6 | import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter; 7 | import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer; 8 | import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer; 9 | 10 | import javax.inject.Inject; 11 | 12 | @Configuration 13 | @EnableAuthorizationServer 14 | public class OAuth2AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter { 15 | 16 | @Inject 17 | private AuthenticationManager authenticationManager; 18 | 19 | @Override 20 | public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { 21 | endpoints.authenticationManager(this.authenticationManager); 22 | } 23 | 24 | @Override 25 | public void configure(ClientDetailsServiceConfigurer clients) throws Exception { 26 | clients.inMemory() 27 | .withClient("oauthclient") 28 | .secret("123456") 29 | .authorizedGrantTypes("password") 30 | .scopes("read", "write") 31 | .resourceIds("OAuth2_Resources"); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/org/sandbox/config/OAuth2ResourceServerConfig.java: -------------------------------------------------------------------------------- 1 | package org.sandbox.config; 2 | 3 | import org.springframework.context.annotation.Configuration; 4 | import org.springframework.security.config.annotation.web.builders.HttpSecurity; 5 | import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; 6 | import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter; 7 | import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer; 8 | 9 | @Configuration 10 | @EnableResourceServer 11 | public class OAuth2ResourceServerConfig extends ResourceServerConfigurerAdapter { 12 | 13 | @Override 14 | public void configure(ResourceServerSecurityConfigurer resources) { 15 | resources.resourceId("OAuth2_Resources"); 16 | } 17 | 18 | @Override 19 | public void configure(HttpSecurity http) throws Exception { 20 | http.requestMatchers().antMatchers("/demo/oauth2/**") 21 | .and() 22 | .authorizeRequests().antMatchers("/demo/oauth2/**").authenticated(); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/org/sandbox/config/RedisConfig.java: -------------------------------------------------------------------------------- 1 | package org.sandbox.config; 2 | 3 | import org.springframework.context.annotation.Bean; 4 | import org.springframework.context.annotation.Configuration; 5 | import org.springframework.data.redis.connection.RedisConnectionFactory; 6 | import org.springframework.data.redis.connection.jedis.JedisConnectionFactory; 7 | import org.springframework.data.redis.core.StringRedisTemplate; 8 | import redis.clients.jedis.JedisPoolConfig; 9 | 10 | /** 11 | * Author: zhangxin 12 | * Date: 15-8-28 13 | */ 14 | @Configuration 15 | public class RedisConfig { 16 | @Bean 17 | public RedisConnectionFactory jedisConnectionFactory(){ 18 | JedisPoolConfig poolConfig=new JedisPoolConfig(); 19 | poolConfig.setMaxIdle(5); 20 | poolConfig.setMinIdle(1); 21 | poolConfig.setTestOnBorrow(true); 22 | poolConfig.setTestOnReturn(true); 23 | poolConfig.setTestWhileIdle(true); 24 | poolConfig.setNumTestsPerEvictionRun(10); 25 | poolConfig.setTimeBetweenEvictionRunsMillis(60000); 26 | 27 | JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(poolConfig); 28 | jedisConnectionFactory.setHostName("127.0.0.1"); 29 | jedisConnectionFactory.setPort(6379); 30 | jedisConnectionFactory.setDatabase(1); 31 | jedisConnectionFactory.setPassword("1234567890"); 32 | return jedisConnectionFactory; 33 | } 34 | 35 | @Bean 36 | public StringRedisTemplate redisTemplate() { 37 | StringRedisTemplate redisTemplate = new StringRedisTemplate(jedisConnectionFactory()); 38 | return redisTemplate; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/org/sandbox/config/ShiroConfig.java: -------------------------------------------------------------------------------- 1 | package org.sandbox.config; 2 | 3 | //import org.apache.shiro.realm.text.PropertiesRealm; 4 | //import org.apache.shiro.spring.LifecycleBeanPostProcessor; 5 | //import org.apache.shiro.spring.web.ShiroFilterFactoryBean; 6 | //import org.apache.shiro.web.filter.authc.AnonymousFilter; 7 | //import org.apache.shiro.web.filter.authc.FormAuthenticationFilter; 8 | //import org.apache.shiro.web.filter.authc.LogoutFilter; 9 | //import org.apache.shiro.web.filter.authc.UserFilter; 10 | //import org.apache.shiro.web.filter.authz.RolesAuthorizationFilter; 11 | //import org.apache.shiro.web.mgt.DefaultWebSecurityManager; 12 | //import org.springframework.context.annotation.Bean; 13 | import org.springframework.context.annotation.Configuration; 14 | //import org.springframework.context.annotation.DependsOn; 15 | // 16 | //import javax.servlet.Filter; 17 | //import java.util.HashMap; 18 | //import java.util.Map; 19 | 20 | /** 21 | * Author: zhangxin 22 | * Date: 15-10-20 23 | */ 24 | @Configuration 25 | public class ShiroConfig { 26 | 27 | // @Bean(name = "shiroFilter") 28 | // public ShiroFilterFactoryBean shiroFilter() { 29 | // ShiroFilterFactoryBean shiroFilter = new ShiroFilterFactoryBean(); 30 | // shiroFilter.setLoginUrl("/login"); 31 | // shiroFilter.setSuccessUrl("/index"); 32 | // shiroFilter.setUnauthorizedUrl("/forbidden"); 33 | // shiroFilter.setSecurityManager(securityManager()); 34 | // 35 | // Map filterChainDefinitionMapping = new HashMap<>(); 36 | // filterChainDefinitionMapping.put("/", "anon"); 37 | // filterChainDefinitionMapping.put("/home", "authc,roles[guest]"); 38 | // filterChainDefinitionMapping.put("/admin", "authc,roles[admin]"); 39 | // shiroFilter.setFilterChainDefinitionMap(filterChainDefinitionMapping); 40 | // 41 | // Map filters = new HashMap<>(); 42 | // filters.put("anon", new AnonymousFilter()); 43 | // filters.put("authc", new FormAuthenticationFilter()); 44 | // filters.put("logout", new LogoutFilter()); 45 | // filters.put("roles", new RolesAuthorizationFilter()); 46 | // filters.put("user", new UserFilter()); 47 | // shiroFilter.setFilters(filters); 48 | // 49 | // return shiroFilter; 50 | // } 51 | // 52 | // @Bean(name = "securityManager") 53 | // public DefaultWebSecurityManager securityManager() { 54 | // DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager(); 55 | // securityManager.setRealm(realm()); 56 | // return securityManager; 57 | // } 58 | // 59 | // @Bean(name = "realm") 60 | // @DependsOn("lifecycleBeanPostProcessor") 61 | // public PropertiesRealm realm() { 62 | // PropertiesRealm propertiesRealm = new PropertiesRealm(); 63 | // propertiesRealm.init(); 64 | // return propertiesRealm; 65 | // } 66 | // 67 | // @Bean 68 | // public LifecycleBeanPostProcessor lifecycleBeanPostProcessor() { 69 | // return new LifecycleBeanPostProcessor(); 70 | // } 71 | } 72 | -------------------------------------------------------------------------------- /src/main/java/org/sandbox/config/SwaggerConfig.java: -------------------------------------------------------------------------------- 1 | package org.sandbox.config; 2 | 3 | import com.mangofactory.swagger.configuration.SpringSwaggerConfig; 4 | import com.mangofactory.swagger.models.dto.ApiInfo; 5 | import com.mangofactory.swagger.models.dto.builder.ApiInfoBuilder; 6 | import com.mangofactory.swagger.plugin.EnableSwagger; 7 | import com.mangofactory.swagger.plugin.SwaggerSpringMvcPlugin; 8 | import org.springframework.context.annotation.Bean; 9 | import org.springframework.context.annotation.Configuration; 10 | 11 | import javax.inject.Inject; 12 | 13 | /** 14 | * Author: zhangxin 15 | * Date: 15-9-17 16 | */ 17 | @Configuration 18 | @EnableSwagger 19 | public class SwaggerConfig { 20 | 21 | @Inject 22 | private SpringSwaggerConfig springSwaggerConfig; 23 | 24 | private ApiInfo getApiInfo() { 25 | 26 | ApiInfo apiInfo = new ApiInfoBuilder() 27 | .title("Spring Boot Example API") 28 | .description("Spring Boot Example API") 29 | .termsOfServiceUrl("http://example.com/terms-of-service") 30 | .contact("info@example.com") 31 | .license("MIT License") 32 | .licenseUrl("http://opensource.org/licenses/MIT") 33 | .build(); 34 | 35 | return apiInfo; 36 | } 37 | 38 | @Bean 39 | public SwaggerSpringMvcPlugin apiConfiguration() { 40 | SwaggerSpringMvcPlugin swaggerSpringMvcPlugin = new SwaggerSpringMvcPlugin(this.springSwaggerConfig); 41 | swaggerSpringMvcPlugin 42 | .apiInfo(getApiInfo()).apiVersion("0.1") 43 | .includePatterns("/demo/v1/persons/*.*").swaggerGroup("v1"); 44 | swaggerSpringMvcPlugin.useDefaultResponseMessages(false); 45 | return swaggerSpringMvcPlugin; 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/org/sandbox/config/TaskConfig.java: -------------------------------------------------------------------------------- 1 | package org.sandbox.config; 2 | 3 | import org.springframework.scheduling.annotation.EnableScheduling; 4 | import org.springframework.scheduling.annotation.Scheduled; 5 | import org.springframework.stereotype.Component; 6 | 7 | import java.text.SimpleDateFormat; 8 | import java.util.Date; 9 | 10 | /** 11 | * Author: zhangxin 12 | * Date: 15-9-15 13 | */ 14 | @Component 15 | //@EnableScheduling 16 | public class TaskConfig { 17 | private final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss"); 18 | private static int count = 0; 19 | 20 | //fixedRate: 从上一个任务开始到下一个任务开始的间隔,单位是毫秒。 21 | @Scheduled(fixedRate = 5000) 22 | public void reportCurrentTime() { 23 | System.out.println("The time is now " + simpleDateFormat.format(new Date())); 24 | } 25 | 26 | @Scheduled(cron = "0/1 * * * * ?") 27 | public void repeatShowMsg() { 28 | System.out.println("repeat show message: " + (++count)); 29 | } 30 | 31 | //fixedDelay: 表示从上一个任务完成开始到下一个任务开始的间隔,单位是毫秒。 32 | @Scheduled(fixedDelay = 10000) 33 | public void fixedDelayShowMsg() { 34 | System.out.println("fixed delay show message ... "); 35 | } 36 | 37 | @Scheduled(initialDelay = 10000, fixedRate = 6000) 38 | public void initialDelayShowMsg() { 39 | System.out.println("initial delay show message!"); 40 | } 41 | 42 | @Scheduled(fixedRateString = "10000") 43 | public void fixedRateStringShowMsg() { 44 | System.out.println("fixed rate string show message ... "); 45 | } 46 | 47 | @Scheduled(fixedDelayString = "10000") 48 | public void fixedDelayStringShowMsg() { 49 | System.out.println("fixed delay string show message ..."); 50 | } 51 | 52 | @Scheduled(initialDelayString = "10000", fixedDelayString = "10000") 53 | public void initialDelayStringShowMsg() { 54 | System.out.println("initial delay string show message ..."); 55 | } 56 | 57 | @Scheduled(initialDelay = 10000, fixedDelay = Long.MAX_VALUE) 58 | public void runOnceMsg() { 59 | System.out.println("only run once message!!"); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/main/java/org/sandbox/config/UrlRewriteConfig.java: -------------------------------------------------------------------------------- 1 | package org.sandbox.config; 2 | 3 | import org.springframework.boot.context.embedded.FilterRegistrationBean; 4 | import org.springframework.boot.context.embedded.ServletRegistrationBean; 5 | import org.springframework.context.annotation.Bean; 6 | import org.springframework.context.annotation.Configuration; 7 | import org.springframework.web.servlet.DispatcherServlet; 8 | 9 | import javax.servlet.DispatcherType; 10 | 11 | /** 12 | * Author: zhangxin 13 | * Date: 15-8-29 14 | */ 15 | @Configuration 16 | public class UrlRewriteConfig { 17 | 18 | @Bean 19 | public FilterRegistrationBean filterRegistrationBean() { 20 | FilterRegistrationBean registrationBean = new FilterRegistrationBean(); 21 | registrationBean.setFilter(new CustomUrlRewriteFilter()); 22 | registrationBean.addUrlPatterns("/*"); 23 | registrationBean.setDispatcherTypes(DispatcherType.REQUEST); 24 | 25 | return registrationBean; 26 | } 27 | 28 | @Bean 29 | public DispatcherServlet dispatcherServlet() { 30 | return new DispatcherServlet(); 31 | } 32 | 33 | @Bean 34 | public ServletRegistrationBean dispatcherServletRegistration() { 35 | ServletRegistrationBean registration = new ServletRegistrationBean(dispatcherServlet(), "/*"); 36 | 37 | // registration.setName(DispatcherServletAutoConfiguration.DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME); 38 | 39 | registration.setName("spring-boot-mybatis"); 40 | 41 | return registration; 42 | } 43 | 44 | 45 | // @Bean 46 | // public UrlRewriteFilter urlRewriteFilter() { 47 | // UrlRewriteFilter urlRewriteFilter = new UrlRewriteFilter(); 48 | // return urlRewriteFilter; 49 | // } 50 | 51 | 52 | // @Bean 53 | // public ServletRegistrationBean dispatcherRegistration(DispatcherServlet dispatcherServlet) { 54 | // ServletRegistrationBean registration = new ServletRegistrationBean(dispatcherServlet); 55 | // registration.addUrlMappings("/app/*"); 56 | // return registration; 57 | // } 58 | 59 | // @Bean 60 | // public FilterRegistrationBean filterRegistrationBean() 61 | // { 62 | // FilterRegistrationBean registrationBean = new FilterRegistrationBean(); 63 | // 64 | // registrationBean.setFilter(new UrlRewriteFilter()); 65 | // registrationBean.addUrlPatterns("*"); 66 | // registrationBean.addInitParameter("confReloadCheckInterval", "5"); 67 | // registrationBean.addInitParameter("logLevel", "DEBUG"); 68 | // 69 | // return registrationBean; 70 | // } 71 | 72 | // @Bean 73 | // public UrlRewriteFilter urlRewriteFilter() { 74 | // UrlRewriteFilter urlRewriteFilter = new EnhancedUrlRewriteFilter(); 75 | // return urlRewriteFilter; 76 | // } 77 | } 78 | -------------------------------------------------------------------------------- /src/main/java/org/sandbox/config/WebSecurityConfig.java: -------------------------------------------------------------------------------- 1 | package org.sandbox.config; 2 | 3 | import org.springframework.context.annotation.Bean; 4 | import org.springframework.context.annotation.Configuration; 5 | import org.springframework.core.Ordered; 6 | import org.springframework.core.annotation.Order; 7 | import org.springframework.security.authentication.AuthenticationManager; 8 | import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; 9 | import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; 10 | import org.springframework.security.config.annotation.web.builders.HttpSecurity; 11 | import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; 12 | import org.springframework.security.config.annotation.web.servlet.configuration.EnableWebMvcSecurity; 13 | import org.springframework.security.config.http.SessionCreationPolicy; 14 | import org.springframework.security.core.userdetails.UserDetailsService; 15 | import org.springframework.security.web.authentication.www.BasicAuthenticationFilter; 16 | import org.springframework.security.web.authentication.www.DigestAuthenticationEntryPoint; 17 | import org.springframework.security.web.authentication.www.DigestAuthenticationFilter; 18 | import org.springframework.security.web.csrf.CsrfTokenRepository; 19 | import org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository; 20 | 21 | /** 22 | * Created by zhangxin on 15/9/10. 23 | */ 24 | @Configuration 25 | @EnableWebMvcSecurity 26 | @EnableGlobalMethodSecurity(prePostEnabled = true) 27 | public class WebSecurityConfig extends WebSecurityConfigurerAdapter { 28 | 29 | /** 30 | * Digest Authentication 31 | * */ 32 | 33 | @Bean 34 | public DigestAuthenticationEntryPoint digestEntryPoint() { 35 | DigestAuthenticationEntryPoint entryPoint = new DigestAuthenticationEntryPoint(); 36 | entryPoint.setRealmName("Custom Realm Name"); 37 | entryPoint.setKey("uniqueAndSecret"); 38 | return entryPoint; 39 | } 40 | 41 | @Bean 42 | public DigestAuthenticationFilter digestFilter() throws Exception { 43 | DigestAuthenticationFilter filter = new DigestAuthenticationFilter(); 44 | filter.setAuthenticationEntryPoint(digestEntryPoint()); 45 | filter.setUserDetailsService(userDetailsServiceBean()); 46 | return filter; 47 | } 48 | 49 | @Override 50 | @Bean 51 | public UserDetailsService userDetailsServiceBean() throws Exception { 52 | return super.userDetailsServiceBean(); 53 | } 54 | 55 | @Override 56 | protected void configure(AuthenticationManagerBuilder auth) throws Exception { 57 | auth.inMemoryAuthentication() 58 | .withUser("zhangxin").password("123456").roles("USER_ROLE") 59 | .and() 60 | .withUser("test").password("test").roles("**"); 61 | } 62 | 63 | @Override 64 | protected void configure(HttpSecurity http) throws Exception { 65 | http.exceptionHandling() 66 | .authenticationEntryPoint(digestEntryPoint()) 67 | .and() 68 | .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) 69 | .and() 70 | .authorizeRequests() 71 | .antMatchers("/demo/v1/persons/**", "/demo/mongo/customers/**").permitAll() 72 | .antMatchers("/demo/security/**").authenticated() 73 | .and() 74 | .addFilterAfter(digestFilter(), BasicAuthenticationFilter.class) 75 | .csrf().disable(); 76 | // .csrf().csrfTokenRepository(csrfTokenRepository()); 77 | } 78 | 79 | @Override 80 | @Bean 81 | protected AuthenticationManager authenticationManager() throws Exception { 82 | return super.authenticationManager(); 83 | } 84 | 85 | private CsrfTokenRepository csrfTokenRepository() 86 | { 87 | HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository(); 88 | repository.setSessionAttributeName("_csrf"); 89 | return repository; 90 | } 91 | 92 | /** 93 | * Basic Authentication 94 | * */ 95 | 96 | // @Override 97 | // protected void configure(AuthenticationManagerBuilder auth) throws Exception { 98 | // auth.inMemoryAuthentication() 99 | // .withUser("test").password("test").roles("USER_ROLE"); 100 | // } 101 | // 102 | // @Override 103 | // @Order(Ordered.HIGHEST_PRECEDENCE) 104 | // protected void configure(HttpSecurity http) throws Exception { 105 | // http.sessionManagement() 106 | // .sessionCreationPolicy(SessionCreationPolicy.STATELESS) 107 | // .and() 108 | // .authorizeRequests() 109 | // .antMatchers("/demo/v1/persons/**", "/demo/mongo/customers/**").permitAll() 110 | // .antMatchers("/demo/security/**").authenticated() 111 | // .and() 112 | // .httpBasic() 113 | // .realmName("Spring Demo") 114 | // .and() 115 | // .csrf() 116 | // .disable(); 117 | // } 118 | // 119 | // @Override 120 | // @Bean 121 | // protected AuthenticationManager authenticationManager() throws Exception { 122 | // return super.authenticationManager(); 123 | // } 124 | } 125 | -------------------------------------------------------------------------------- /src/main/java/org/sandbox/controller/ArrayParamsController.java: -------------------------------------------------------------------------------- 1 | package org.sandbox.controller; 2 | 3 | import org.springframework.http.HttpStatus; 4 | import org.springframework.http.ResponseEntity; 5 | import org.springframework.web.bind.annotation.*; 6 | 7 | /** 8 | * Created by zhangxin on 15/9/19. 9 | */ 10 | @RestController 11 | @RequestMapping(value = "array") 12 | public class ArrayParamsController { 13 | 14 | @RequestMapping(method = RequestMethod.GET) 15 | @ResponseBody 16 | public ResponseEntity testArrayParam(@RequestParam("params")String[] params) { 17 | 18 | for(int i = 0; i < params.length; i++) { 19 | System.out.println(params[i]); 20 | } 21 | 22 | return new ResponseEntity<>(null, HttpStatus.OK); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/org/sandbox/controller/ExampleExceptionController.java: -------------------------------------------------------------------------------- 1 | package org.sandbox.controller; 2 | 3 | import org.sandbox.exception.CustomException; 4 | import org.sandbox.exception.ValidateObject; 5 | import org.springframework.http.HttpHeaders; 6 | import org.springframework.http.HttpStatus; 7 | import org.springframework.http.ResponseEntity; 8 | import org.springframework.web.bind.annotation.*; 9 | import org.springframework.web.servlet.support.ServletUriComponentsBuilder; 10 | 11 | import javax.validation.Valid; 12 | import java.net.URI; 13 | 14 | /** 15 | * Author: zhangxin 16 | * Date: 15-9-17 17 | */ 18 | @RestController 19 | @RequestMapping(value = "demo/v1/") 20 | public class ExampleExceptionController { 21 | 22 | @RequestMapping(value = "exceptions/{id}", method = RequestMethod.GET) 23 | public ResponseEntity getException(@PathVariable("id")String id) { 24 | if(id.equals("0")) 25 | throw new CustomException("ha ha, got exception."); 26 | 27 | return new ResponseEntity<>("no exception.", null, HttpStatus.OK); 28 | } 29 | 30 | @RequestMapping(value = "exceptions/validate", method = RequestMethod.POST) 31 | public ResponseEntity addValidObject(@Valid @RequestBody ValidateObject validateObject) { 32 | HttpHeaders headers = new HttpHeaders(); 33 | URI newUri = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(validateObject.getId()).toUri(); 34 | headers.setLocation(newUri); 35 | 36 | return new ResponseEntity<>(null, headers, HttpStatus.CREATED); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/org/sandbox/controller/HateoasController.java: -------------------------------------------------------------------------------- 1 | package org.sandbox.controller; 2 | 3 | import org.sandbox.hateoas.Article; 4 | import org.sandbox.orm.Person; 5 | import org.springframework.http.HttpStatus; 6 | import org.springframework.http.ResponseEntity; 7 | import org.springframework.web.bind.annotation.PathVariable; 8 | import org.springframework.web.bind.annotation.RequestMapping; 9 | import org.springframework.web.bind.annotation.RequestMethod; 10 | import org.springframework.web.bind.annotation.RestController; 11 | 12 | import java.util.ArrayList; 13 | import java.util.List; 14 | 15 | import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo; 16 | import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn; 17 | 18 | /** 19 | * Author: zhangxin 20 | * Date: 15-9-18 21 | */ 22 | @RestController 23 | @RequestMapping("hateoas/") 24 | public class HateoasController { 25 | 26 | @RequestMapping(value = "articles/{title}", method = RequestMethod.GET) 27 | public ResponseEntity getArticles(@PathVariable("title")String title) { 28 | Article article = new Article(title, "spring-boot", "1234567890987654321", 19, System.currentTimeMillis()); 29 | article.add(linkTo(methodOn(HateoasController.class).getArticles(title)).withSelfRel()); 30 | article.add(linkTo(methodOn(PersonController.class).getPerson(5)).withRel("author")); 31 | article.add(linkTo(methodOn(PersonController.class).setPersonObject(new Person())).withRel("author_obj")); 32 | return new ResponseEntity<>(article, HttpStatus.OK); 33 | } 34 | 35 | @RequestMapping(value = "articles", method = RequestMethod.GET) 36 | public ResponseEntity getArticleSet() { 37 | List
articleList = new ArrayList<>(); 38 | for(int i = 0; i < 10; i++) { 39 | Article article = new Article("article_" + i, "spring boot example", "content_" + i, 40 | "spring boot example".length(), System.currentTimeMillis()); 41 | 42 | article.add(linkTo(methodOn(HateoasController.class).getArticles(article.getTitle())).withSelfRel()); 43 | article.add(linkTo(methodOn(PersonController.class).getPerson(i)).withRel("author")); 44 | articleList.add(article); 45 | } 46 | 47 | return new ResponseEntity<>(articleList, HttpStatus.OK); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/org/sandbox/controller/JmsController.java: -------------------------------------------------------------------------------- 1 | package org.sandbox.controller; 2 | 3 | import org.sandbox.service.JmsProducerService; 4 | import org.springframework.beans.factory.annotation.Autowired; 5 | import org.springframework.http.HttpStatus; 6 | import org.springframework.http.ResponseEntity; 7 | import org.springframework.web.bind.annotation.RequestMapping; 8 | import org.springframework.web.bind.annotation.RequestMethod; 9 | import org.springframework.web.bind.annotation.RequestParam; 10 | import org.springframework.web.bind.annotation.RestController; 11 | 12 | /** 13 | * Author: zhangxin 14 | * Date: 15-9-7 15 | */ 16 | @RestController 17 | @RequestMapping(value = "demo/jms") 18 | public class JmsController { 19 | 20 | @Autowired 21 | private JmsProducerService jmsProducerService; 22 | 23 | @RequestMapping(method = RequestMethod.POST) 24 | public ResponseEntity sendMsg(@RequestParam("msg")String msg) { 25 | jmsProducerService.sendMsg(msg); 26 | return new ResponseEntity<>(null, HttpStatus.OK); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/org/sandbox/controller/MongoController.java: -------------------------------------------------------------------------------- 1 | package org.sandbox.controller; 2 | 3 | import org.sandbox.mongodb.Customer; 4 | import org.sandbox.service.MongoService; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.http.HttpStatus; 7 | import org.springframework.http.ResponseEntity; 8 | import org.springframework.web.bind.annotation.*; 9 | 10 | import java.util.List; 11 | 12 | /** 13 | * Author: zhangxin 14 | * Date: 15-9-1 15 | */ 16 | @RestController 17 | @RequestMapping(value = "/demo/mongo") 18 | public class MongoController { 19 | 20 | @Autowired 21 | private MongoService mongoService; 22 | 23 | @RequestMapping(value = "customers/{firstName}", method = RequestMethod.GET, produces = "application/json;charset=UTF-8") 24 | public ResponseEntity getCustomersByFirstName(@PathVariable("firstName")String firstName) { 25 | Customer customer = mongoService.getCustomerByFirstName(firstName); 26 | return new ResponseEntity<>(customer, HttpStatus.OK); 27 | } 28 | 29 | @RequestMapping(value = "customers/lastname/{lastName}", method = RequestMethod.GET) 30 | public ResponseEntity getCustomersByLastName(@PathVariable("lastName")String lastName) { 31 | List customers = mongoService.getCustomerByLastName(lastName); 32 | return new ResponseEntity<>(customers, HttpStatus.OK); 33 | } 34 | 35 | @RequestMapping(value = "customers", method = RequestMethod.POST) 36 | public ResponseEntity addCustomer(@RequestParam("firstName")String firstName, @RequestParam("lastName")String lastName) { 37 | mongoService.insert(firstName, lastName); 38 | return new ResponseEntity<>("insert successfully", HttpStatus.CREATED); 39 | } 40 | 41 | @RequestMapping(value = "customers/{id}", method = RequestMethod.DELETE) 42 | public ResponseEntity delCustomer(@PathVariable("id")String id) { 43 | mongoService.delete(id); 44 | return new ResponseEntity<>("delete successfully", HttpStatus.OK); 45 | } 46 | 47 | @RequestMapping(value = "customers/{id}", method = RequestMethod.PUT) 48 | public ResponseEntity updateCustomer(@PathVariable("id")String id, @RequestParam("firstName") String firstName, 49 | @RequestParam("lastName")String lastName) { 50 | mongoService.update(id, firstName, lastName); 51 | return new ResponseEntity<>("update successfully", HttpStatus.OK); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/main/java/org/sandbox/controller/OAuthController.java: -------------------------------------------------------------------------------- 1 | package org.sandbox.controller; 2 | 3 | import org.sandbox.service.OAuthService; 4 | import org.springframework.beans.factory.annotation.Autowired; 5 | import org.springframework.http.HttpStatus; 6 | import org.springframework.http.ResponseEntity; 7 | import org.springframework.web.bind.annotation.RequestMapping; 8 | import org.springframework.web.bind.annotation.RequestMethod; 9 | import org.springframework.web.bind.annotation.RestController; 10 | 11 | /** 12 | * Author: zhangxin 13 | * Date: 15-9-12 14 | */ 15 | @RestController 16 | @RequestMapping(value = "demo/oauth2") 17 | public class OAuthController { 18 | 19 | @Autowired 20 | private OAuthService oAuthService; 21 | 22 | @RequestMapping(method = RequestMethod.GET) 23 | public ResponseEntity getOAuth() { 24 | String msg = oAuthService.getOAuth(); 25 | return new ResponseEntity<>(msg, HttpStatus.OK); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/org/sandbox/controller/PersonController.java: -------------------------------------------------------------------------------- 1 | package org.sandbox.controller; 2 | 3 | import com.wordnik.swagger.annotations.Api; 4 | import com.wordnik.swagger.annotations.ApiOperation; 5 | import com.wordnik.swagger.annotations.ApiResponse; 6 | import com.wordnik.swagger.annotations.ApiResponses; 7 | import org.sandbox.exception.ErrorDetail; 8 | import org.sandbox.orm.Person; 9 | import org.sandbox.service.PersonService; 10 | import org.springframework.beans.factory.annotation.Autowired; 11 | import org.springframework.http.HttpStatus; 12 | import org.springframework.http.ResponseEntity; 13 | import org.springframework.util.LinkedMultiValueMap; 14 | import org.springframework.util.MultiValueMap; 15 | import org.springframework.web.bind.annotation.*; 16 | 17 | /** 18 | * Created by zhangxin on 15/8/27. 19 | */ 20 | @RestController 21 | @RequestMapping(value = "/demo/v1/") 22 | @Api(value = "person", description = "Spring Boot Example Persion Controller") 23 | public class PersonController { 24 | @Autowired 25 | private PersonService personService; 26 | 27 | @RequestMapping(value = "persons/{id}", method = RequestMethod.GET) 28 | @ResponseBody 29 | @ApiOperation(value = "Fetch API", notes = "Fetch person by id", response = Person.class) 30 | @ApiResponses(value = {@ApiResponse(code = 500, message = "Server Error", response = ErrorDetail.class)}) 31 | public Object getPerson(@PathVariable int id) { 32 | return personService.select(id); 33 | } 34 | 35 | @RequestMapping(value = "persons", method = RequestMethod.POST) 36 | @ApiOperation(value = "POST API", notes = "Add new person by multiple params into database", response = String.class) 37 | @ApiResponses(value = {@ApiResponse(code = 500, message = "server error", response = ErrorDetail.class)}) 38 | public ResponseEntity setPerson(@RequestParam("name")String name, 39 | @RequestParam("age")int age, 40 | @RequestParam("country")String country) { 41 | Person person = new Person(); 42 | person.setName(name); 43 | person.setAge(age); 44 | person.setCountry(country); 45 | 46 | int id = personService.insert(person); 47 | 48 | MultiValueMap headers = new LinkedMultiValueMap<>(); 49 | headers.set("location", "http://localhost:8080/persons/" + id); 50 | 51 | return new ResponseEntity<>("ResponseEntity insert successfully", headers, HttpStatus.OK); 52 | } 53 | 54 | @RequestMapping(value = "persons/object", method = RequestMethod.POST) 55 | @ResponseBody 56 | @ApiOperation(value = "Set API", notes = "Add new person by person object into database", response = String.class) 57 | @ApiResponses(value = {@ApiResponse(code = 500, message = "server error", response = ErrorDetail.class)}) 58 | public Object setPersonObject(@RequestBody Person person) { 59 | personService.insert(person); 60 | return "insert successfully."; 61 | } 62 | 63 | @RequestMapping(value = "persons/{id}", method = RequestMethod.PUT) 64 | @ApiOperation(value = "Update API", notes = "Update person by id and multiply params", response = String.class) 65 | @ApiResponses(value = {@ApiResponse(code = 500, message = "server error", response = ErrorDetail.class)}) 66 | public ResponseEntity updatePerson(@PathVariable("id") int id, @RequestParam("name") String name, 67 | @RequestParam("age") int age, 68 | @RequestParam("country") String country) { 69 | Person person = new Person(); 70 | person.setId(id); 71 | person.setName(name); 72 | person.setAge(age); 73 | person.setCountry(country); 74 | 75 | personService.update(person); 76 | 77 | return new ResponseEntity<>("update successfully", HttpStatus.OK); 78 | } 79 | 80 | @RequestMapping(value = "persons/object/{id}", method = RequestMethod.PUT) 81 | @ApiOperation(value = "Update API", notes = "Update person by id and person object params into database", response = String.class) 82 | @ApiResponses(value = {@ApiResponse(code = 500, message = "server error", response = ErrorDetail.class)}) 83 | public ResponseEntity updatePersonObject(@PathVariable("id") int id, @RequestBody Person person) { 84 | person.setId(id); 85 | personService.update(person); 86 | 87 | return new ResponseEntity<>("update successfully", HttpStatus.OK); 88 | } 89 | 90 | @RequestMapping(value = "persons/{id}", method = RequestMethod.DELETE) 91 | @ApiOperation(value = "Delete API", notes = "Delete person by id", response = Void.class) 92 | @ApiResponses(value = {@ApiResponse(code = 500, message = "server error", response = ErrorDetail.class)}) 93 | public ResponseEntity delPerson(@PathVariable int id) { 94 | personService.delete(id); 95 | return new ResponseEntity<>(null, HttpStatus.OK); 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /src/main/java/org/sandbox/controller/ProfilesController.java: -------------------------------------------------------------------------------- 1 | package org.sandbox.controller; 2 | 3 | import org.springframework.beans.factory.annotation.Value; 4 | import org.springframework.web.bind.annotation.RequestMapping; 5 | import org.springframework.web.bind.annotation.RequestMethod; 6 | import org.springframework.web.bind.annotation.ResponseBody; 7 | import org.springframework.web.bind.annotation.RestController; 8 | 9 | /** 10 | * Author: zhangxin 11 | * Date: 15-12-2 12 | */ 13 | @RestController 14 | @RequestMapping(value = "profile") 15 | public class ProfilesController { 16 | 17 | @Value("${name}") 18 | private String name; 19 | 20 | @RequestMapping(method = RequestMethod.GET) 21 | @ResponseBody 22 | public Object getName() { 23 | return name; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/org/sandbox/controller/RedisController.java: -------------------------------------------------------------------------------- 1 | package org.sandbox.controller; 2 | 3 | import org.sandbox.service.RedisService; 4 | import org.springframework.beans.factory.annotation.Autowired; 5 | import org.springframework.http.HttpStatus; 6 | import org.springframework.http.ResponseEntity; 7 | import org.springframework.web.bind.annotation.RequestMapping; 8 | import org.springframework.web.bind.annotation.RequestMethod; 9 | import org.springframework.web.bind.annotation.RequestParam; 10 | import org.springframework.web.bind.annotation.RestController; 11 | 12 | /** 13 | * Author: zhangxin 14 | * Date: 15-8-28 15 | */ 16 | @RestController 17 | @RequestMapping(value = "v1") 18 | public class RedisController { 19 | @Autowired 20 | private RedisService redisService; 21 | 22 | @RequestMapping(value = "redis", method = RequestMethod.GET) 23 | public ResponseEntity getValue(@RequestParam("key")String key) { 24 | return new ResponseEntity<>(redisService.getValue(key), HttpStatus.OK); 25 | } 26 | 27 | @RequestMapping(value = "redis", method = RequestMethod.POST) 28 | public ResponseEntity setValue(@RequestParam("key")String key, @RequestParam("value")String value) { 29 | redisService.setValue(key, value); 30 | return new ResponseEntity<>("set key/value successfully", HttpStatus.OK); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/org/sandbox/controller/SecurityController.java: -------------------------------------------------------------------------------- 1 | package org.sandbox.controller; 2 | 3 | import org.sandbox.service.SecurityService; 4 | import org.springframework.beans.factory.annotation.Autowired; 5 | import org.springframework.http.HttpStatus; 6 | import org.springframework.http.ResponseEntity; 7 | import org.springframework.web.bind.annotation.RequestMapping; 8 | import org.springframework.web.bind.annotation.RequestMethod; 9 | import org.springframework.web.bind.annotation.RestController; 10 | 11 | /** 12 | * Author: zhangxin 13 | * Date: 15-9-10 14 | */ 15 | @RestController 16 | @RequestMapping(value = "demo/security") 17 | public class SecurityController { 18 | 19 | @Autowired 20 | private SecurityService securityService; 21 | 22 | @RequestMapping(value = "security", method = RequestMethod.GET) 23 | public ResponseEntity security() { 24 | String msg = securityService.secure(); 25 | return new ResponseEntity<>(msg, HttpStatus.OK); 26 | } 27 | 28 | @RequestMapping(value = "authorized", method = RequestMethod.GET) 29 | public ResponseEntity auhtorized() { 30 | String msg = securityService.authorized(); 31 | return new ResponseEntity<>(msg, HttpStatus.OK); 32 | } 33 | 34 | @RequestMapping(value = "denied", method = RequestMethod.GET) 35 | public ResponseEntity denied() { 36 | String msg = securityService.denied(); 37 | return new ResponseEntity<>(msg, HttpStatus.OK); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/org/sandbox/exception/CustomException.java: -------------------------------------------------------------------------------- 1 | package org.sandbox.exception; 2 | 3 | import org.springframework.http.HttpStatus; 4 | import org.springframework.web.bind.annotation.ResponseStatus; 5 | 6 | /** 7 | * Author: zhangxin 8 | * Date: 15-9-17 9 | */ 10 | @ResponseStatus(value = HttpStatus.NOT_FOUND) 11 | public class CustomException extends RuntimeException { 12 | private static final long serialVersionUID = 1L; 13 | 14 | public CustomException() { 15 | super(); 16 | } 17 | 18 | public CustomException(String message) { 19 | super(message); 20 | } 21 | 22 | public CustomException(String message, Throwable throwable) { 23 | super(message, throwable); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/org/sandbox/exception/ErrorDetail.java: -------------------------------------------------------------------------------- 1 | package org.sandbox.exception; 2 | 3 | import java.util.HashMap; 4 | import java.util.List; 5 | import java.util.Map; 6 | 7 | /** 8 | * Author: zhangxin 9 | * Date: 15-9-17 10 | */ 11 | public class ErrorDetail { 12 | 13 | private String title; 14 | private int status; 15 | private String detail; 16 | private long timestamp; 17 | private String developerMessage; 18 | private Map> errors = new HashMap<>(); 19 | 20 | public String getTitle() { 21 | return title; 22 | } 23 | 24 | public void setTitle(String title) { 25 | this.title = title; 26 | } 27 | 28 | public int getStatus() { 29 | return status; 30 | } 31 | 32 | public void setStatus(int status) { 33 | this.status = status; 34 | } 35 | 36 | public String getDetail() { 37 | return detail; 38 | } 39 | 40 | public void setDetail(String detail) { 41 | this.detail = detail; 42 | } 43 | 44 | public long getTimestamp() { 45 | return timestamp; 46 | } 47 | 48 | public void setTimestamp(long timestamp) { 49 | this.timestamp = timestamp; 50 | } 51 | 52 | public String getDeveloperMessage() { 53 | return developerMessage; 54 | } 55 | 56 | public void setDeveloperMessage(String developerMessage) { 57 | this.developerMessage = developerMessage; 58 | } 59 | 60 | public Map> getErrors() { 61 | return errors; 62 | } 63 | 64 | public void setErrors(Map> errors) { 65 | this.errors = errors; 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/main/java/org/sandbox/exception/ExampleExceptionHandler.java: -------------------------------------------------------------------------------- 1 | package org.sandbox.exception; 2 | 3 | import org.springframework.context.MessageSource; 4 | import org.springframework.http.HttpHeaders; 5 | import org.springframework.http.HttpStatus; 6 | import org.springframework.http.ResponseEntity; 7 | import org.springframework.validation.FieldError; 8 | import org.springframework.web.bind.MethodArgumentNotValidException; 9 | import org.springframework.web.bind.annotation.ControllerAdvice; 10 | import org.springframework.web.bind.annotation.ExceptionHandler; 11 | import org.springframework.web.context.request.WebRequest; 12 | import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; 13 | 14 | import javax.inject.Inject; 15 | import java.util.ArrayList; 16 | import java.util.List; 17 | 18 | /** 19 | * Author: zhangxin 20 | * Date: 15-9-17 21 | */ 22 | @ControllerAdvice 23 | public class ExampleExceptionHandler extends ResponseEntityExceptionHandler { 24 | 25 | @Inject 26 | private MessageSource messageSource; 27 | 28 | @ExceptionHandler(CustomException.class) 29 | public ResponseEntity handleExampleException(CustomException ce) { 30 | ErrorDetail errorDetail = new ErrorDetail(); 31 | errorDetail.setTitle("Custom Exception"); 32 | errorDetail.setStatus(HttpStatus.NOT_FOUND.value()); 33 | errorDetail.setDetail(ce.getMessage()); 34 | errorDetail.setTimestamp(System.currentTimeMillis()); 35 | errorDetail.setDeveloperMessage(ce.getClass().getName()); 36 | 37 | return new ResponseEntity<>(errorDetail, null, HttpStatus.NOT_FOUND); 38 | } 39 | 40 | @Override 41 | public ResponseEntity handleMethodArgumentNotValid(MethodArgumentNotValidException manve, HttpHeaders headers, 42 | HttpStatus status, WebRequest request) { 43 | 44 | ErrorDetail errorDetail = new ErrorDetail(); 45 | errorDetail.setTimestamp(System.currentTimeMillis()); 46 | errorDetail.setStatus(HttpStatus.BAD_REQUEST.value()); 47 | errorDetail.setTitle("Validation Failed"); 48 | errorDetail.setDetail("Input validation failed"); 49 | errorDetail.setDeveloperMessage(manve.getClass().getName()); 50 | 51 | List fieldErrors = manve.getBindingResult().getFieldErrors(); 52 | for(FieldError fe: fieldErrors) { 53 | List validationErrorList = errorDetail.getErrors().get(fe.getField()); 54 | if(validationErrorList == null) { 55 | validationErrorList = new ArrayList<>(); 56 | errorDetail.getErrors().put(fe.getField(), validationErrorList); 57 | } 58 | ValidationError validationError = new ValidationError(); 59 | validationError.setCode(fe.getCode()); 60 | validationError.setMessage(messageSource.getMessage(fe, null)); 61 | validationErrorList.add(validationError); 62 | } 63 | 64 | return handleExceptionInternal(manve, errorDetail, headers, status, request); 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /src/main/java/org/sandbox/exception/ValidateObject.java: -------------------------------------------------------------------------------- 1 | package org.sandbox.exception; 2 | 3 | import org.hibernate.validator.constraints.NotEmpty; 4 | 5 | import javax.validation.constraints.Size; 6 | 7 | /** 8 | * Author: zhangxin 9 | * Date: 15-9-17 10 | */ 11 | public class ValidateObject { 12 | 13 | @NotEmpty 14 | private String id; 15 | 16 | @Size(min = 2, max = 6) 17 | private String name; 18 | 19 | public String getId() { 20 | return id; 21 | } 22 | 23 | public void setId(String id) { 24 | this.id = id; 25 | } 26 | 27 | public String getName() { 28 | return name; 29 | } 30 | 31 | public void setName(String name) { 32 | this.name = name; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/org/sandbox/exception/ValidationError.java: -------------------------------------------------------------------------------- 1 | package org.sandbox.exception; 2 | 3 | /** 4 | * Author: zhangxin 5 | * Date: 15-9-17 6 | */ 7 | public class ValidationError { 8 | 9 | private String code; 10 | private String message; 11 | 12 | public String getCode() { 13 | return code; 14 | } 15 | 16 | public void setCode(String code) { 17 | this.code = code; 18 | } 19 | 20 | public String getMessage() { 21 | return message; 22 | } 23 | 24 | public void setMessage(String message) { 25 | this.message = message; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/org/sandbox/hateoas/Article.java: -------------------------------------------------------------------------------- 1 | package org.sandbox.hateoas; 2 | 3 | import org.springframework.hateoas.ResourceSupport; 4 | 5 | /** 6 | * Author: zhangxin 7 | * Date: 15-9-18 8 | */ 9 | public class Article extends ResourceSupport { 10 | private String title; 11 | private String author; 12 | private String content; 13 | private Integer len; 14 | private Long timestamp; 15 | 16 | public Article(String title, String author, String content, Integer len, Long timestamp) { 17 | this.title = title; 18 | this.author = author; 19 | this.content = content; 20 | this.len = len; 21 | this.timestamp = timestamp; 22 | } 23 | 24 | public String getTitle() { 25 | return title; 26 | } 27 | 28 | public void setTitle(String title) { 29 | this.title = title; 30 | } 31 | 32 | public String getAuthor() { 33 | return author; 34 | } 35 | 36 | public void setAuthor(String author) { 37 | this.author = author; 38 | } 39 | 40 | public String getContent() { 41 | return content; 42 | } 43 | 44 | public void setContent(String content) { 45 | this.content = content; 46 | } 47 | 48 | public Integer getLen() { 49 | return len; 50 | } 51 | 52 | public void setLen(Integer len) { 53 | this.len = len; 54 | } 55 | 56 | public Long getTimestamp() { 57 | return timestamp; 58 | } 59 | 60 | public void setTimestamp(Long timestamp) { 61 | this.timestamp = timestamp; 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/main/java/org/sandbox/mongodb/Customer.java: -------------------------------------------------------------------------------- 1 | package org.sandbox.mongodb; 2 | 3 | import org.springframework.data.annotation.Id; 4 | 5 | /** 6 | * Author: zhangxin 7 | * Date: 15-9-1 8 | */ 9 | public class Customer { 10 | 11 | @Id 12 | private String id; 13 | 14 | private String firstName; 15 | private String lastName; 16 | 17 | public Customer() { 18 | } 19 | 20 | public Customer(String firstName, String lastName) { 21 | this.firstName = firstName; 22 | this.lastName = lastName; 23 | } 24 | 25 | public String getId() { 26 | return id; 27 | } 28 | 29 | public void setId(String id) { 30 | this.id = id; 31 | } 32 | 33 | public String getFirstName() { 34 | return firstName; 35 | } 36 | 37 | public void setFirstName(String firstName) { 38 | this.firstName = firstName; 39 | } 40 | 41 | public String getLastName() { 42 | return lastName; 43 | } 44 | 45 | public void setLastName(String lastName) { 46 | this.lastName = lastName; 47 | } 48 | 49 | @Override 50 | public String toString() { 51 | return String.format("Customer[id=%s, firstName='%s', lastName='%s']", id, 52 | firstName, lastName); 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/main/java/org/sandbox/mongodb/CustomerRepository.java: -------------------------------------------------------------------------------- 1 | package org.sandbox.mongodb; 2 | 3 | import org.springframework.data.mongodb.repository.MongoRepository; 4 | 5 | import java.util.List; 6 | 7 | /** 8 | * Author: zhangxin 9 | * Date: 15-9-1 10 | */ 11 | public interface CustomerRepository extends MongoRepository, CustomerRepositoryCustom { 12 | Customer findByFirstName(String firstName); 13 | List findByLastName(String lastName); 14 | } -------------------------------------------------------------------------------- /src/main/java/org/sandbox/mongodb/CustomerRepositoryCustom.java: -------------------------------------------------------------------------------- 1 | package org.sandbox.mongodb; 2 | 3 | import java.util.List; 4 | 5 | /** 6 | * Author: zhangxin 7 | * Date: 15-9-7 8 | */ 9 | public interface CustomerRepositoryCustom { 10 | List getCustomerByLastName(String lastName); 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/org/sandbox/mongodb/CustomerRepositoryImpl.java: -------------------------------------------------------------------------------- 1 | package org.sandbox.mongodb; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.data.mongodb.core.MongoTemplate; 5 | import org.springframework.data.mongodb.core.query.Criteria; 6 | import org.springframework.data.mongodb.core.query.Query; 7 | 8 | import java.util.List; 9 | 10 | /** 11 | * Author: zhangxin 12 | * Date: 15-9-7 13 | */ 14 | public class CustomerRepositoryImpl implements CustomerRepositoryCustom { 15 | 16 | @Autowired 17 | private MongoTemplate template; 18 | 19 | @Override 20 | public List getCustomerByLastName(String lastName) { 21 | Criteria criteria = Criteria.where("lastName").is(lastName); 22 | return template.find(Query.query(criteria), Customer.class); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/org/sandbox/orm/Person.java: -------------------------------------------------------------------------------- 1 | package org.sandbox.orm; 2 | 3 | public class Person { 4 | private Integer id; 5 | 6 | private String name; 7 | 8 | private Integer age; 9 | 10 | private String country; 11 | 12 | public Integer getId() { 13 | return id; 14 | } 15 | 16 | public void setId(Integer id) { 17 | this.id = id; 18 | } 19 | 20 | public String getName() { 21 | return name; 22 | } 23 | 24 | public void setName(String name) { 25 | this.name = name == null ? null : name.trim(); 26 | } 27 | 28 | public Integer getAge() { 29 | return age; 30 | } 31 | 32 | public void setAge(Integer age) { 33 | this.age = age; 34 | } 35 | 36 | public String getCountry() { 37 | return country; 38 | } 39 | 40 | public void setCountry(String country) { 41 | this.country = country == null ? null : country.trim(); 42 | } 43 | 44 | @Override 45 | public String toString() { 46 | return "Person{" + 47 | "id=" + id + 48 | ", name='" + name + '\'' + 49 | ", age=" + age + 50 | ", country='" + country + '\'' + 51 | '}'; 52 | } 53 | } -------------------------------------------------------------------------------- /src/main/java/org/sandbox/orm/PersonDao.java: -------------------------------------------------------------------------------- 1 | package org.sandbox.orm; 2 | 3 | import org.mybatis.spring.support.SqlSessionDaoSupport; 4 | import org.slf4j.Logger; 5 | import org.slf4j.LoggerFactory; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | 8 | import java.util.List; 9 | 10 | /** 11 | * Author: zhangxin 12 | * Date: 15-9-16 13 | */ 14 | public class PersonDao extends SqlSessionDaoSupport { 15 | 16 | private Logger logger = LoggerFactory.getLogger(this.getClass()); 17 | 18 | @Autowired 19 | private PersonMapper personMapper; 20 | 21 | public Person select(int id) { 22 | logger.info("###PersonDao### select person, id is " + id); 23 | 24 | PersonExample example = new PersonExample(); 25 | PersonExample.Criteria criteria = example.createCriteria(); 26 | criteria.andIdEqualTo(id); 27 | List persons = personMapper.selectByExample(example); 28 | if(persons != null && persons.size() > 0) { 29 | return persons.get(0); 30 | } 31 | 32 | return null; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/org/sandbox/orm/PersonExample.java: -------------------------------------------------------------------------------- 1 | package org.sandbox.orm; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | public class PersonExample { 7 | protected String orderByClause; 8 | 9 | protected boolean distinct; 10 | 11 | protected List oredCriteria; 12 | 13 | public PersonExample() { 14 | oredCriteria = new ArrayList(); 15 | } 16 | 17 | public void setOrderByClause(String orderByClause) { 18 | this.orderByClause = orderByClause; 19 | } 20 | 21 | public String getOrderByClause() { 22 | return orderByClause; 23 | } 24 | 25 | public void setDistinct(boolean distinct) { 26 | this.distinct = distinct; 27 | } 28 | 29 | public boolean isDistinct() { 30 | return distinct; 31 | } 32 | 33 | public List getOredCriteria() { 34 | return oredCriteria; 35 | } 36 | 37 | public void or(Criteria criteria) { 38 | oredCriteria.add(criteria); 39 | } 40 | 41 | public Criteria or() { 42 | Criteria criteria = createCriteriaInternal(); 43 | oredCriteria.add(criteria); 44 | return criteria; 45 | } 46 | 47 | public Criteria createCriteria() { 48 | Criteria criteria = createCriteriaInternal(); 49 | if (oredCriteria.size() == 0) { 50 | oredCriteria.add(criteria); 51 | } 52 | return criteria; 53 | } 54 | 55 | protected Criteria createCriteriaInternal() { 56 | Criteria criteria = new Criteria(); 57 | return criteria; 58 | } 59 | 60 | public void clear() { 61 | oredCriteria.clear(); 62 | orderByClause = null; 63 | distinct = false; 64 | } 65 | 66 | protected abstract static class GeneratedCriteria { 67 | protected List criteria; 68 | 69 | protected GeneratedCriteria() { 70 | super(); 71 | criteria = new ArrayList(); 72 | } 73 | 74 | public boolean isValid() { 75 | return criteria.size() > 0; 76 | } 77 | 78 | public List getAllCriteria() { 79 | return criteria; 80 | } 81 | 82 | public List getCriteria() { 83 | return criteria; 84 | } 85 | 86 | protected void addCriterion(String condition) { 87 | if (condition == null) { 88 | throw new RuntimeException("Value for condition cannot be null"); 89 | } 90 | criteria.add(new Criterion(condition)); 91 | } 92 | 93 | protected void addCriterion(String condition, Object value, String property) { 94 | if (value == null) { 95 | throw new RuntimeException("Value for " + property + " cannot be null"); 96 | } 97 | criteria.add(new Criterion(condition, value)); 98 | } 99 | 100 | protected void addCriterion(String condition, Object value1, Object value2, String property) { 101 | if (value1 == null || value2 == null) { 102 | throw new RuntimeException("Between values for " + property + " cannot be null"); 103 | } 104 | criteria.add(new Criterion(condition, value1, value2)); 105 | } 106 | 107 | public Criteria andIdIsNull() { 108 | addCriterion("id is null"); 109 | return (Criteria) this; 110 | } 111 | 112 | public Criteria andIdIsNotNull() { 113 | addCriterion("id is not null"); 114 | return (Criteria) this; 115 | } 116 | 117 | public Criteria andIdEqualTo(Integer value) { 118 | addCriterion("id =", value, "id"); 119 | return (Criteria) this; 120 | } 121 | 122 | public Criteria andIdNotEqualTo(Integer value) { 123 | addCriterion("id <>", value, "id"); 124 | return (Criteria) this; 125 | } 126 | 127 | public Criteria andIdGreaterThan(Integer value) { 128 | addCriterion("id >", value, "id"); 129 | return (Criteria) this; 130 | } 131 | 132 | public Criteria andIdGreaterThanOrEqualTo(Integer value) { 133 | addCriterion("id >=", value, "id"); 134 | return (Criteria) this; 135 | } 136 | 137 | public Criteria andIdLessThan(Integer value) { 138 | addCriterion("id <", value, "id"); 139 | return (Criteria) this; 140 | } 141 | 142 | public Criteria andIdLessThanOrEqualTo(Integer value) { 143 | addCriterion("id <=", value, "id"); 144 | return (Criteria) this; 145 | } 146 | 147 | public Criteria andIdIn(List values) { 148 | addCriterion("id in", values, "id"); 149 | return (Criteria) this; 150 | } 151 | 152 | public Criteria andIdNotIn(List values) { 153 | addCriterion("id not in", values, "id"); 154 | return (Criteria) this; 155 | } 156 | 157 | public Criteria andIdBetween(Integer value1, Integer value2) { 158 | addCriterion("id between", value1, value2, "id"); 159 | return (Criteria) this; 160 | } 161 | 162 | public Criteria andIdNotBetween(Integer value1, Integer value2) { 163 | addCriterion("id not between", value1, value2, "id"); 164 | return (Criteria) this; 165 | } 166 | 167 | public Criteria andNameIsNull() { 168 | addCriterion("name is null"); 169 | return (Criteria) this; 170 | } 171 | 172 | public Criteria andNameIsNotNull() { 173 | addCriterion("name is not null"); 174 | return (Criteria) this; 175 | } 176 | 177 | public Criteria andNameEqualTo(String value) { 178 | addCriterion("name =", value, "name"); 179 | return (Criteria) this; 180 | } 181 | 182 | public Criteria andNameNotEqualTo(String value) { 183 | addCriterion("name <>", value, "name"); 184 | return (Criteria) this; 185 | } 186 | 187 | public Criteria andNameGreaterThan(String value) { 188 | addCriterion("name >", value, "name"); 189 | return (Criteria) this; 190 | } 191 | 192 | public Criteria andNameGreaterThanOrEqualTo(String value) { 193 | addCriterion("name >=", value, "name"); 194 | return (Criteria) this; 195 | } 196 | 197 | public Criteria andNameLessThan(String value) { 198 | addCriterion("name <", value, "name"); 199 | return (Criteria) this; 200 | } 201 | 202 | public Criteria andNameLessThanOrEqualTo(String value) { 203 | addCriterion("name <=", value, "name"); 204 | return (Criteria) this; 205 | } 206 | 207 | public Criteria andNameLike(String value) { 208 | addCriterion("name like", value, "name"); 209 | return (Criteria) this; 210 | } 211 | 212 | public Criteria andNameNotLike(String value) { 213 | addCriterion("name not like", value, "name"); 214 | return (Criteria) this; 215 | } 216 | 217 | public Criteria andNameIn(List values) { 218 | addCriterion("name in", values, "name"); 219 | return (Criteria) this; 220 | } 221 | 222 | public Criteria andNameNotIn(List values) { 223 | addCriterion("name not in", values, "name"); 224 | return (Criteria) this; 225 | } 226 | 227 | public Criteria andNameBetween(String value1, String value2) { 228 | addCriterion("name between", value1, value2, "name"); 229 | return (Criteria) this; 230 | } 231 | 232 | public Criteria andNameNotBetween(String value1, String value2) { 233 | addCriterion("name not between", value1, value2, "name"); 234 | return (Criteria) this; 235 | } 236 | 237 | public Criteria andAgeIsNull() { 238 | addCriterion("age is null"); 239 | return (Criteria) this; 240 | } 241 | 242 | public Criteria andAgeIsNotNull() { 243 | addCriterion("age is not null"); 244 | return (Criteria) this; 245 | } 246 | 247 | public Criteria andAgeEqualTo(Integer value) { 248 | addCriterion("age =", value, "age"); 249 | return (Criteria) this; 250 | } 251 | 252 | public Criteria andAgeNotEqualTo(Integer value) { 253 | addCriterion("age <>", value, "age"); 254 | return (Criteria) this; 255 | } 256 | 257 | public Criteria andAgeGreaterThan(Integer value) { 258 | addCriterion("age >", value, "age"); 259 | return (Criteria) this; 260 | } 261 | 262 | public Criteria andAgeGreaterThanOrEqualTo(Integer value) { 263 | addCriterion("age >=", value, "age"); 264 | return (Criteria) this; 265 | } 266 | 267 | public Criteria andAgeLessThan(Integer value) { 268 | addCriterion("age <", value, "age"); 269 | return (Criteria) this; 270 | } 271 | 272 | public Criteria andAgeLessThanOrEqualTo(Integer value) { 273 | addCriterion("age <=", value, "age"); 274 | return (Criteria) this; 275 | } 276 | 277 | public Criteria andAgeIn(List values) { 278 | addCriterion("age in", values, "age"); 279 | return (Criteria) this; 280 | } 281 | 282 | public Criteria andAgeNotIn(List values) { 283 | addCriterion("age not in", values, "age"); 284 | return (Criteria) this; 285 | } 286 | 287 | public Criteria andAgeBetween(Integer value1, Integer value2) { 288 | addCriterion("age between", value1, value2, "age"); 289 | return (Criteria) this; 290 | } 291 | 292 | public Criteria andAgeNotBetween(Integer value1, Integer value2) { 293 | addCriterion("age not between", value1, value2, "age"); 294 | return (Criteria) this; 295 | } 296 | 297 | public Criteria andCountryIsNull() { 298 | addCriterion("country is null"); 299 | return (Criteria) this; 300 | } 301 | 302 | public Criteria andCountryIsNotNull() { 303 | addCriterion("country is not null"); 304 | return (Criteria) this; 305 | } 306 | 307 | public Criteria andCountryEqualTo(String value) { 308 | addCriterion("country =", value, "country"); 309 | return (Criteria) this; 310 | } 311 | 312 | public Criteria andCountryNotEqualTo(String value) { 313 | addCriterion("country <>", value, "country"); 314 | return (Criteria) this; 315 | } 316 | 317 | public Criteria andCountryGreaterThan(String value) { 318 | addCriterion("country >", value, "country"); 319 | return (Criteria) this; 320 | } 321 | 322 | public Criteria andCountryGreaterThanOrEqualTo(String value) { 323 | addCriterion("country >=", value, "country"); 324 | return (Criteria) this; 325 | } 326 | 327 | public Criteria andCountryLessThan(String value) { 328 | addCriterion("country <", value, "country"); 329 | return (Criteria) this; 330 | } 331 | 332 | public Criteria andCountryLessThanOrEqualTo(String value) { 333 | addCriterion("country <=", value, "country"); 334 | return (Criteria) this; 335 | } 336 | 337 | public Criteria andCountryLike(String value) { 338 | addCriterion("country like", value, "country"); 339 | return (Criteria) this; 340 | } 341 | 342 | public Criteria andCountryNotLike(String value) { 343 | addCriterion("country not like", value, "country"); 344 | return (Criteria) this; 345 | } 346 | 347 | public Criteria andCountryIn(List values) { 348 | addCriterion("country in", values, "country"); 349 | return (Criteria) this; 350 | } 351 | 352 | public Criteria andCountryNotIn(List values) { 353 | addCriterion("country not in", values, "country"); 354 | return (Criteria) this; 355 | } 356 | 357 | public Criteria andCountryBetween(String value1, String value2) { 358 | addCriterion("country between", value1, value2, "country"); 359 | return (Criteria) this; 360 | } 361 | 362 | public Criteria andCountryNotBetween(String value1, String value2) { 363 | addCriterion("country not between", value1, value2, "country"); 364 | return (Criteria) this; 365 | } 366 | } 367 | 368 | public static class Criteria extends GeneratedCriteria { 369 | 370 | protected Criteria() { 371 | super(); 372 | } 373 | } 374 | 375 | public static class Criterion { 376 | private String condition; 377 | 378 | private Object value; 379 | 380 | private Object secondValue; 381 | 382 | private boolean noValue; 383 | 384 | private boolean singleValue; 385 | 386 | private boolean betweenValue; 387 | 388 | private boolean listValue; 389 | 390 | private String typeHandler; 391 | 392 | public String getCondition() { 393 | return condition; 394 | } 395 | 396 | public Object getValue() { 397 | return value; 398 | } 399 | 400 | public Object getSecondValue() { 401 | return secondValue; 402 | } 403 | 404 | public boolean isNoValue() { 405 | return noValue; 406 | } 407 | 408 | public boolean isSingleValue() { 409 | return singleValue; 410 | } 411 | 412 | public boolean isBetweenValue() { 413 | return betweenValue; 414 | } 415 | 416 | public boolean isListValue() { 417 | return listValue; 418 | } 419 | 420 | public String getTypeHandler() { 421 | return typeHandler; 422 | } 423 | 424 | protected Criterion(String condition) { 425 | super(); 426 | this.condition = condition; 427 | this.typeHandler = null; 428 | this.noValue = true; 429 | } 430 | 431 | protected Criterion(String condition, Object value, String typeHandler) { 432 | super(); 433 | this.condition = condition; 434 | this.value = value; 435 | this.typeHandler = typeHandler; 436 | if (value instanceof List) { 437 | this.listValue = true; 438 | } else { 439 | this.singleValue = true; 440 | } 441 | } 442 | 443 | protected Criterion(String condition, Object value) { 444 | this(condition, value, null); 445 | } 446 | 447 | protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { 448 | super(); 449 | this.condition = condition; 450 | this.value = value; 451 | this.secondValue = secondValue; 452 | this.typeHandler = typeHandler; 453 | this.betweenValue = true; 454 | } 455 | 456 | protected Criterion(String condition, Object value, Object secondValue) { 457 | this(condition, value, secondValue, null); 458 | } 459 | } 460 | } -------------------------------------------------------------------------------- /src/main/java/org/sandbox/orm/PersonMapper.java: -------------------------------------------------------------------------------- 1 | package org.sandbox.orm; 2 | 3 | import java.util.List; 4 | import org.apache.ibatis.annotations.Delete; 5 | import org.apache.ibatis.annotations.Insert; 6 | import org.apache.ibatis.annotations.Param; 7 | import org.apache.ibatis.annotations.ResultMap; 8 | import org.apache.ibatis.annotations.Select; 9 | import org.apache.ibatis.annotations.SelectKey; 10 | import org.apache.ibatis.annotations.Update; 11 | import org.sandbox.orm.Person; 12 | import org.sandbox.orm.PersonExample; 13 | 14 | public interface PersonMapper { 15 | int countByExample(PersonExample example); 16 | 17 | int deleteByExample(PersonExample example); 18 | 19 | @Delete({ 20 | "delete from person", 21 | "where id = #{id,jdbcType=INTEGER}" 22 | }) 23 | int deleteByPrimaryKey(Integer id); 24 | 25 | @Insert({ 26 | "insert into person (name, age, ", 27 | "country)", 28 | "values (#{name,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER}, ", 29 | "#{country,jdbcType=VARCHAR})" 30 | }) 31 | @SelectKey(statement="SELECT LAST_INSERT_ID()", keyProperty="id", before=false, resultType=Integer.class) 32 | int insert(Person record); 33 | 34 | int insertSelective(Person record); 35 | 36 | List selectByExample(PersonExample example); 37 | 38 | @Select({ 39 | "select", 40 | "id, name, age, country", 41 | "from person", 42 | "where id = #{id,jdbcType=INTEGER}" 43 | }) 44 | @ResultMap("BaseResultMap") 45 | Person selectByPrimaryKey(Integer id); 46 | 47 | int updateByExampleSelective(@Param("record") Person record, @Param("example") PersonExample example); 48 | 49 | int updateByExample(@Param("record") Person record, @Param("example") PersonExample example); 50 | 51 | int updateByPrimaryKeySelective(Person record); 52 | 53 | @Update({ 54 | "update person", 55 | "set name = #{name,jdbcType=VARCHAR},", 56 | "age = #{age,jdbcType=INTEGER},", 57 | "country = #{country,jdbcType=VARCHAR}", 58 | "where id = #{id,jdbcType=INTEGER}" 59 | }) 60 | int updateByPrimaryKey(Person record); 61 | } -------------------------------------------------------------------------------- /src/main/java/org/sandbox/service/JmsConsumerService.java: -------------------------------------------------------------------------------- 1 | package org.sandbox.service; 2 | 3 | import org.springframework.jms.annotation.JmsListener; 4 | import org.springframework.stereotype.Service; 5 | 6 | /** 7 | * Author: zhangxin 8 | * Date: 15-9-7 9 | */ 10 | @Service 11 | public class JmsConsumerService { 12 | 13 | @JmsListener(destination = "sample.queue") 14 | public void recvQueue(String txt) { 15 | System.out.println("consumer receive msg: " + txt); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/org/sandbox/service/JmsProducerService.java: -------------------------------------------------------------------------------- 1 | package org.sandbox.service; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.jms.core.JmsMessagingTemplate; 5 | import org.springframework.stereotype.Service; 6 | 7 | import javax.jms.Queue; 8 | 9 | /** 10 | * Author: zhangxin 11 | * Date: 15-9-7 12 | */ 13 | @Service 14 | public class JmsProducerService { 15 | 16 | @Autowired 17 | private JmsMessagingTemplate jmsMessagingTemplate; 18 | 19 | @Autowired 20 | private Queue queue; 21 | 22 | public void sendMsg(String msg) { 23 | jmsMessagingTemplate.convertAndSend(queue, msg); 24 | System.out.println("Message was sent to the Queue"); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/org/sandbox/service/MongoService.java: -------------------------------------------------------------------------------- 1 | package org.sandbox.service; 2 | 3 | import org.sandbox.mongodb.Customer; 4 | import org.sandbox.mongodb.CustomerRepository; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.data.mongodb.core.MongoTemplate; 7 | import org.springframework.data.mongodb.core.query.Criteria; 8 | import org.springframework.data.mongodb.core.query.Query; 9 | import org.springframework.stereotype.Service; 10 | 11 | import java.util.List; 12 | 13 | /** 14 | * Author: zhangxin 15 | * Date: 15-9-1 16 | */ 17 | @Service 18 | public class MongoService { 19 | 20 | @Autowired 21 | private CustomerRepository repository; 22 | 23 | public Customer getCustomerByFirstName(String firstName) { 24 | return repository.findByFirstName(firstName); 25 | } 26 | 27 | public List getCustomerByLastName(String lastName) { 28 | return repository.findByLastName(lastName); 29 | } 30 | 31 | public void insert(String firstName, String lastName) { 32 | repository.save(new Customer(firstName, lastName)); 33 | } 34 | 35 | public void delete(String id) { 36 | repository.delete(id); 37 | } 38 | 39 | public void update(String id, String firstName, String lastName) { 40 | Customer customer = repository.findOne(id); 41 | customer.setFirstName(firstName); 42 | customer.setLastName(lastName); 43 | repository.save(customer); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/org/sandbox/service/OAuthService.java: -------------------------------------------------------------------------------- 1 | package org.sandbox.service; 2 | 3 | import org.springframework.security.access.annotation.Secured; 4 | import org.springframework.stereotype.Service; 5 | 6 | /** 7 | * Author: zhangxin 8 | * Date: 15-9-12 9 | */ 10 | @Service 11 | public class OAuthService { 12 | 13 | @Secured("USER_ROLE") 14 | public String getOAuth() { 15 | return "Hello OAuth"; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/org/sandbox/service/PersonService.java: -------------------------------------------------------------------------------- 1 | package org.sandbox.service; 2 | 3 | import org.sandbox.orm.Person; 4 | import org.sandbox.orm.PersonDao; 5 | import org.sandbox.orm.PersonExample; 6 | import org.sandbox.orm.PersonMapper; 7 | import org.slf4j.Logger; 8 | import org.slf4j.LoggerFactory; 9 | import org.springframework.beans.factory.annotation.Autowired; 10 | import org.springframework.stereotype.Service; 11 | 12 | import javax.transaction.Transactional; 13 | import java.util.List; 14 | 15 | /** 16 | * Author: zhangxin 17 | * Date: 15-8-28 18 | */ 19 | @Service 20 | @Transactional 21 | public class PersonService { 22 | private final Logger logger = LoggerFactory.getLogger(this.getClass()); 23 | 24 | @Autowired 25 | private PersonMapper personMapper; 26 | 27 | @Autowired 28 | private PersonDao personDao; 29 | 30 | public int insert(Person person) { 31 | logger.info("add person"); 32 | 33 | personMapper.insertSelective(person); 34 | 35 | //为了测试事务回滚 36 | //throw new IllegalArgumentException("roll back"); 37 | 38 | return 1; 39 | } 40 | 41 | public int update(Person person) { 42 | logger.info("update person"); 43 | 44 | PersonExample example = new PersonExample(); 45 | PersonExample.Criteria criteria = example.createCriteria(); 46 | criteria.andIdEqualTo(person.getId()); 47 | 48 | return personMapper.updateByExample(person, example); 49 | } 50 | 51 | public int delete(int id) { 52 | logger.info("delete person, id is " + id); 53 | 54 | return personMapper.deleteByPrimaryKey(id); 55 | } 56 | 57 | public Person select(int id) { 58 | // logger.info("select person, id is " + id); 59 | // 60 | // PersonExample example = new PersonExample(); 61 | // PersonExample.Criteria criteria = example.createCriteria(); 62 | // criteria.andIdEqualTo(id); 63 | // List persons = personMapper.selectByExample(example); 64 | // if(persons != null && persons.size() > 0) { 65 | // return persons.get(0); 66 | // } 67 | // return null; 68 | return personDao.select(id); 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /src/main/java/org/sandbox/service/RedisService.java: -------------------------------------------------------------------------------- 1 | package org.sandbox.service; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.data.redis.core.RedisTemplate; 5 | import org.springframework.stereotype.Service; 6 | 7 | import java.util.Random; 8 | import java.util.concurrent.TimeUnit; 9 | 10 | /** 11 | * Author: zhangxin 12 | * Date: 15-8-28 13 | */ 14 | @Service 15 | public class RedisService { 16 | private final Random random = new Random(); 17 | 18 | @Autowired 19 | private RedisTemplate redisTemplate; 20 | 21 | public String getValue(String key) { 22 | return redisTemplate.opsForValue().get(key); 23 | } 24 | 25 | public void setValue(String key, String value) { 26 | redisTemplate.opsForValue().set(key, value); 27 | int timeout = random.nextInt(86400); 28 | redisTemplate.expire(key, timeout, TimeUnit.SECONDS); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/org/sandbox/service/SecurityService.java: -------------------------------------------------------------------------------- 1 | package org.sandbox.service; 2 | 3 | import org.springframework.security.access.annotation.Secured; 4 | import org.springframework.security.access.prepost.PreAuthorize; 5 | import org.springframework.stereotype.Service; 6 | 7 | /** 8 | * Author: zhangxin 9 | * Date: 15-9-10 10 | */ 11 | @Service 12 | public class SecurityService { 13 | 14 | @Secured("USER_ROLE") 15 | public String secure() { 16 | return "Hello Security"; 17 | } 18 | 19 | @PreAuthorize("true") 20 | public String authorized() { 21 | return "Hello world"; 22 | } 23 | 24 | @PreAuthorize("false") 25 | public String denied() { 26 | return "Denied"; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/main/resources/application-dev.properties: -------------------------------------------------------------------------------- 1 | name=!!!develop!!! -------------------------------------------------------------------------------- /src/main/resources/application-pro.properties: -------------------------------------------------------------------------------- 1 | name=!!!production!!! -------------------------------------------------------------------------------- /src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | spring.main.show-banner=false 2 | 3 | #spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?autoReconnect=true&useCompression=true&useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true 4 | #spring.datasource.username=root 5 | #spring.datasource.password=mysql 6 | #spring.datasource.driver-class-name=com.mysql.jdbc.Driver 7 | #spring.datasource.max-active=30 8 | #spring.datasource.maximum-pool-size=100 9 | 10 | spring.data.mongodb.database=test 11 | spring.data.mongodb.port=27017 12 | spring.data.mongodb.uri="mongodb://localhost/test" 13 | #spring.data.mongodb.username= 14 | #spring.data.mongodb.authentication-database= 15 | #spring.data.mongodb.grid-fs-database= 16 | #spring.data.mongodb.host= 17 | #spring.data.mongodb.password[]= 18 | #spring.data.mongodb.repositories.enabled= 19 | 20 | #spring.activemq.broker-url= 21 | #spring.activemq.user= 22 | #spring.activemq.password= 23 | #spring.activemq.in-memory= 24 | spring.activemq.pooled=true 25 | 26 | 27 | #security.user.name=user 28 | #security.user.password=123456 29 | #security.basic.enabled=false 30 | 31 | logging.level.org.springframework.web: DEBUG 32 | logging.level.org.springframework.security: DEBUG 33 | 34 | spring.messages.basename=messages 35 | spring.messages.cache-seconds=-1 36 | spring.messages.encoding=UTF-8 37 | 38 | spring.profiles.active=pro -------------------------------------------------------------------------------- /src/main/resources/logback.properties: -------------------------------------------------------------------------------- 1 | log.path=./logs/ 2 | log.name=demo.log 3 | log.name.error=demo-error.log -------------------------------------------------------------------------------- /src/main/resources/logback.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | System.out 6 | 7 | %d [%t] %p %logger - %m%n 8 | 9 | 10 | DEBUG 11 | 12 | 13 | 14 | ${log.path}/${log.name} 15 | true 16 | 17 | %d [%t] %p %logger{0} - %m%n 18 | 19 | 20 | INFO 21 | 22 | 23 | ${log.path}/${log.name}.%d{yyyy-MM-dd } 24 | 25 | 26 | 27 | ${log.path}/${log.name.error} 28 | 29 | %d [%t] %p %logger{0} - %m%n 30 | 31 | 32 | ERROR 33 | 34 | 35 | ${log.path}/${log.name.error}.%d{yyyy-MM-dd } 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | -------------------------------------------------------------------------------- /src/main/resources/messages.properties: -------------------------------------------------------------------------------- 1 | NotEmpty.validateObject.id=id is a required field 2 | Size.validateObject.name=name must be less than {1} and greater than {2} -------------------------------------------------------------------------------- /src/main/resources/mysql/PersonMapper.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | and ${criterion.condition} 19 | 20 | 21 | and ${criterion.condition} #{criterion.value} 22 | 23 | 24 | and ${criterion.condition} #{criterion.value} and #{criterion.secondValue} 25 | 26 | 27 | and ${criterion.condition} 28 | 29 | #{listItem} 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | and ${criterion.condition} 48 | 49 | 50 | and ${criterion.condition} #{criterion.value} 51 | 52 | 53 | and ${criterion.condition} #{criterion.value} and #{criterion.secondValue} 54 | 55 | 56 | and ${criterion.condition} 57 | 58 | #{listItem} 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | id, name, age, country 70 | 71 | 85 | 86 | delete from person 87 | 88 | 89 | 90 | 91 | 92 | 93 | SELECT LAST_INSERT_ID() 94 | 95 | insert into person 96 | 97 | 98 | name, 99 | 100 | 101 | age, 102 | 103 | 104 | country, 105 | 106 | 107 | 108 | 109 | #{name,jdbcType=VARCHAR}, 110 | 111 | 112 | #{age,jdbcType=INTEGER}, 113 | 114 | 115 | #{country,jdbcType=VARCHAR}, 116 | 117 | 118 | 119 | 125 | 126 | update person 127 | 128 | 129 | id = #{record.id,jdbcType=INTEGER}, 130 | 131 | 132 | name = #{record.name,jdbcType=VARCHAR}, 133 | 134 | 135 | age = #{record.age,jdbcType=INTEGER}, 136 | 137 | 138 | country = #{record.country,jdbcType=VARCHAR}, 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | update person 147 | set id = #{record.id,jdbcType=INTEGER}, 148 | name = #{record.name,jdbcType=VARCHAR}, 149 | age = #{record.age,jdbcType=INTEGER}, 150 | country = #{record.country,jdbcType=VARCHAR} 151 | 152 | 153 | 154 | 155 | 156 | update person 157 | 158 | 159 | name = #{name,jdbcType=VARCHAR}, 160 | 161 | 162 | age = #{age,jdbcType=INTEGER}, 163 | 164 | 165 | country = #{country,jdbcType=VARCHAR}, 166 | 167 | 168 | where id = #{id,jdbcType=INTEGER} 169 | 170 | -------------------------------------------------------------------------------- /src/main/resources/mysql/init.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE `persion` ( 2 | `id` int(11) NOT NULL AUTO_INCREMENT, 3 | `name` varchar(10) NOT NULL, 4 | `age` int(11) NOT NULL, 5 | `country` varchar(10) DEFAULT NULL, 6 | PRIMARY KEY (`id`) 7 | ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -------------------------------------------------------------------------------- /src/main/resources/mysql/mybatis-generator.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 17 | 18 | 19 | 21 | 22 | 23 | 24 | 25 | 27 | 28 | 29 | 30 | 32 | 33 | 34 | 35 | 36 | 37 |
38 | 39 |
40 |
-------------------------------------------------------------------------------- /src/main/resources/static/swagger-ui/css/reset.css: -------------------------------------------------------------------------------- 1 | /* http://meyerweb.com/eric/tools/css/reset/ v2.0 | 20110126 */ 2 | html, 3 | body, 4 | div, 5 | span, 6 | applet, 7 | object, 8 | iframe, 9 | h1, 10 | h2, 11 | h3, 12 | h4, 13 | h5, 14 | h6, 15 | p, 16 | blockquote, 17 | pre, 18 | a, 19 | abbr, 20 | acronym, 21 | address, 22 | big, 23 | cite, 24 | code, 25 | del, 26 | dfn, 27 | em, 28 | img, 29 | ins, 30 | kbd, 31 | q, 32 | s, 33 | samp, 34 | small, 35 | strike, 36 | strong, 37 | sub, 38 | sup, 39 | tt, 40 | var, 41 | b, 42 | u, 43 | i, 44 | center, 45 | dl, 46 | dt, 47 | dd, 48 | ol, 49 | ul, 50 | li, 51 | fieldset, 52 | form, 53 | label, 54 | legend, 55 | table, 56 | caption, 57 | tbody, 58 | tfoot, 59 | thead, 60 | tr, 61 | th, 62 | td, 63 | article, 64 | aside, 65 | canvas, 66 | details, 67 | embed, 68 | figure, 69 | figcaption, 70 | footer, 71 | header, 72 | hgroup, 73 | menu, 74 | nav, 75 | output, 76 | ruby, 77 | section, 78 | summary, 79 | time, 80 | mark, 81 | audio, 82 | video { 83 | margin: 0; 84 | padding: 0; 85 | border: 0; 86 | font-size: 100%; 87 | font: inherit; 88 | vertical-align: baseline; 89 | } 90 | /* HTML5 display-role reset for older browsers */ 91 | article, 92 | aside, 93 | details, 94 | figcaption, 95 | figure, 96 | footer, 97 | header, 98 | hgroup, 99 | menu, 100 | nav, 101 | section { 102 | display: block; 103 | } 104 | body { 105 | line-height: 1; 106 | } 107 | ol, 108 | ul { 109 | list-style: none; 110 | } 111 | blockquote, 112 | q { 113 | quotes: none; 114 | } 115 | blockquote:before, 116 | blockquote:after, 117 | q:before, 118 | q:after { 119 | content: ''; 120 | content: none; 121 | } 122 | table { 123 | border-collapse: collapse; 124 | border-spacing: 0; 125 | } 126 | -------------------------------------------------------------------------------- /src/main/resources/static/swagger-ui/images/explorer_icons.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhangxin23/spring-boot-example/d79c526a385639d5eb5bbb909f347c091738f141/src/main/resources/static/swagger-ui/images/explorer_icons.png -------------------------------------------------------------------------------- /src/main/resources/static/swagger-ui/images/logo_small.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhangxin23/spring-boot-example/d79c526a385639d5eb5bbb909f347c091738f141/src/main/resources/static/swagger-ui/images/logo_small.png -------------------------------------------------------------------------------- /src/main/resources/static/swagger-ui/images/pet_store_api.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhangxin23/spring-boot-example/d79c526a385639d5eb5bbb909f347c091738f141/src/main/resources/static/swagger-ui/images/pet_store_api.png -------------------------------------------------------------------------------- /src/main/resources/static/swagger-ui/images/throbber.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhangxin23/spring-boot-example/d79c526a385639d5eb5bbb909f347c091738f141/src/main/resources/static/swagger-ui/images/throbber.gif -------------------------------------------------------------------------------- /src/main/resources/static/swagger-ui/images/wordnik_api.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhangxin23/spring-boot-example/d79c526a385639d5eb5bbb909f347c091738f141/src/main/resources/static/swagger-ui/images/wordnik_api.png -------------------------------------------------------------------------------- /src/main/resources/static/swagger-ui/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | spring boot example 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 65 | 66 | 67 | 68 | 78 | 79 |
 
80 |
81 | 82 | 83 | -------------------------------------------------------------------------------- /src/main/resources/static/swagger-ui/lib/backbone-min.js: -------------------------------------------------------------------------------- 1 | // Backbone.js 0.9.2 2 | 3 | // (c) 2010-2012 Jeremy Ashkenas, DocumentCloud Inc. 4 | // Backbone may be freely distributed under the MIT license. 5 | // For all details and documentation: 6 | // http://backbonejs.org 7 | (function(){var l=this,y=l.Backbone,z=Array.prototype.slice,A=Array.prototype.splice,g;g="undefined"!==typeof exports?exports:l.Backbone={};g.VERSION="0.9.2";var f=l._;!f&&"undefined"!==typeof require&&(f=require("underscore"));var i=l.jQuery||l.Zepto||l.ender;g.setDomLibrary=function(a){i=a};g.noConflict=function(){l.Backbone=y;return this};g.emulateHTTP=!1;g.emulateJSON=!1;var p=/\s+/,k=g.Events={on:function(a,b,c){var d,e,f,g,j;if(!b)return this;a=a.split(p);for(d=this._callbacks||(this._callbacks= 8 | {});e=a.shift();)f=(j=d[e])?j.tail:{},f.next=g={},f.context=c,f.callback=b,d[e]={tail:g,next:j?j.next:f};return this},off:function(a,b,c){var d,e,h,g,j,q;if(e=this._callbacks){if(!a&&!b&&!c)return delete this._callbacks,this;for(a=a?a.split(p):f.keys(e);d=a.shift();)if(h=e[d],delete e[d],h&&(b||c))for(g=h.tail;(h=h.next)!==g;)if(j=h.callback,q=h.context,b&&j!==b||c&&q!==c)this.on(d,j,q);return this}},trigger:function(a){var b,c,d,e,f,g;if(!(d=this._callbacks))return this;f=d.all;a=a.split(p);for(g= 9 | z.call(arguments,1);b=a.shift();){if(c=d[b])for(e=c.tail;(c=c.next)!==e;)c.callback.apply(c.context||this,g);if(c=f){e=c.tail;for(b=[b].concat(g);(c=c.next)!==e;)c.callback.apply(c.context||this,b)}}return this}};k.bind=k.on;k.unbind=k.off;var o=g.Model=function(a,b){var c;a||(a={});b&&b.parse&&(a=this.parse(a));if(c=n(this,"defaults"))a=f.extend({},c,a);b&&b.collection&&(this.collection=b.collection);this.attributes={};this._escapedAttributes={};this.cid=f.uniqueId("c");this.changed={};this._silent= 10 | {};this._pending={};this.set(a,{silent:!0});this.changed={};this._silent={};this._pending={};this._previousAttributes=f.clone(this.attributes);this.initialize.apply(this,arguments)};f.extend(o.prototype,k,{changed:null,_silent:null,_pending:null,idAttribute:"id",initialize:function(){},toJSON:function(){return f.clone(this.attributes)},get:function(a){return this.attributes[a]},escape:function(a){var b;if(b=this._escapedAttributes[a])return b;b=this.get(a);return this._escapedAttributes[a]=f.escape(null== 11 | b?"":""+b)},has:function(a){return null!=this.get(a)},set:function(a,b,c){var d,e;f.isObject(a)||null==a?(d=a,c=b):(d={},d[a]=b);c||(c={});if(!d)return this;d instanceof o&&(d=d.attributes);if(c.unset)for(e in d)d[e]=void 0;if(!this._validate(d,c))return!1;this.idAttribute in d&&(this.id=d[this.idAttribute]);var b=c.changes={},h=this.attributes,g=this._escapedAttributes,j=this._previousAttributes||{};for(e in d){a=d[e];if(!f.isEqual(h[e],a)||c.unset&&f.has(h,e))delete g[e],(c.silent?this._silent: 12 | b)[e]=!0;c.unset?delete h[e]:h[e]=a;!f.isEqual(j[e],a)||f.has(h,e)!=f.has(j,e)?(this.changed[e]=a,c.silent||(this._pending[e]=!0)):(delete this.changed[e],delete this._pending[e])}c.silent||this.change(c);return this},unset:function(a,b){(b||(b={})).unset=!0;return this.set(a,null,b)},clear:function(a){(a||(a={})).unset=!0;return this.set(f.clone(this.attributes),a)},fetch:function(a){var a=a?f.clone(a):{},b=this,c=a.success;a.success=function(d,e,f){if(!b.set(b.parse(d,f),a))return!1;c&&c(b,d)}; 13 | a.error=g.wrapError(a.error,b,a);return(this.sync||g.sync).call(this,"read",this,a)},save:function(a,b,c){var d,e;f.isObject(a)||null==a?(d=a,c=b):(d={},d[a]=b);c=c?f.clone(c):{};if(c.wait){if(!this._validate(d,c))return!1;e=f.clone(this.attributes)}a=f.extend({},c,{silent:!0});if(d&&!this.set(d,c.wait?a:c))return!1;var h=this,i=c.success;c.success=function(a,b,e){b=h.parse(a,e);if(c.wait){delete c.wait;b=f.extend(d||{},b)}if(!h.set(b,c))return false;i?i(h,a):h.trigger("sync",h,a,c)};c.error=g.wrapError(c.error, 14 | h,c);b=this.isNew()?"create":"update";b=(this.sync||g.sync).call(this,b,this,c);c.wait&&this.set(e,a);return b},destroy:function(a){var a=a?f.clone(a):{},b=this,c=a.success,d=function(){b.trigger("destroy",b,b.collection,a)};if(this.isNew())return d(),!1;a.success=function(e){a.wait&&d();c?c(b,e):b.trigger("sync",b,e,a)};a.error=g.wrapError(a.error,b,a);var e=(this.sync||g.sync).call(this,"delete",this,a);a.wait||d();return e},url:function(){var a=n(this,"urlRoot")||n(this.collection,"url")||t(); 15 | return this.isNew()?a:a+("/"==a.charAt(a.length-1)?"":"/")+encodeURIComponent(this.id)},parse:function(a){return a},clone:function(){return new this.constructor(this.attributes)},isNew:function(){return null==this.id},change:function(a){a||(a={});var b=this._changing;this._changing=!0;for(var c in this._silent)this._pending[c]=!0;var d=f.extend({},a.changes,this._silent);this._silent={};for(c in d)this.trigger("change:"+c,this,this.get(c),a);if(b)return this;for(;!f.isEmpty(this._pending);){this._pending= 16 | {};this.trigger("change",this,a);for(c in this.changed)!this._pending[c]&&!this._silent[c]&&delete this.changed[c];this._previousAttributes=f.clone(this.attributes)}this._changing=!1;return this},hasChanged:function(a){return!arguments.length?!f.isEmpty(this.changed):f.has(this.changed,a)},changedAttributes:function(a){if(!a)return this.hasChanged()?f.clone(this.changed):!1;var b,c=!1,d=this._previousAttributes,e;for(e in a)if(!f.isEqual(d[e],b=a[e]))(c||(c={}))[e]=b;return c},previous:function(a){return!arguments.length|| 17 | !this._previousAttributes?null:this._previousAttributes[a]},previousAttributes:function(){return f.clone(this._previousAttributes)},isValid:function(){return!this.validate(this.attributes)},_validate:function(a,b){if(b.silent||!this.validate)return!0;var a=f.extend({},this.attributes,a),c=this.validate(a,b);if(!c)return!0;b&&b.error?b.error(this,c,b):this.trigger("error",this,c,b);return!1}});var r=g.Collection=function(a,b){b||(b={});b.model&&(this.model=b.model);b.comparator&&(this.comparator=b.comparator); 18 | this._reset();this.initialize.apply(this,arguments);a&&this.reset(a,{silent:!0,parse:b.parse})};f.extend(r.prototype,k,{model:o,initialize:function(){},toJSON:function(a){return this.map(function(b){return b.toJSON(a)})},add:function(a,b){var c,d,e,g,i,j={},k={},l=[];b||(b={});a=f.isArray(a)?a.slice():[a];c=0;for(d=a.length;c=b))this.iframe=i('