├── README.md ├── pom.xml ├── spring-boot-dubbo-plugin ├── pom.xml └── src │ └── main │ └── java │ └── cn │ └── kiiwii │ └── framework │ └── dubbo │ ├── AnnotationBeanConfiguration.java │ ├── DubboProperties.java │ ├── consumer │ └── DubboComsumerConfiguration.java │ └── provider │ └── DubboProviderConfiguration.java ├── spring-boot-with-druid ├── pom.xml └── src │ └── main │ ├── java │ └── cn │ │ └── kiiwii │ │ └── framework │ │ ├── Application.java │ │ ├── aop │ │ ├── ServiceAop.java │ │ └── WebAspect.java │ │ ├── controller │ │ └── TestController.java │ │ ├── dao │ │ ├── ITestDAO.java │ │ └── impl │ │ │ └── TestDAOImpl.java │ │ ├── druid │ │ ├── DruidConfiguration.java │ │ └── DruidDataSourceProperties.java │ │ └── service │ │ ├── ITestService.java │ │ └── impl │ │ └── TestServiceImpl.java │ ├── resources │ ├── application.properties │ └── log4j.properties │ └── script │ └── test.sql ├── spring-boot-with-dubbo ├── dobbo-consumer │ ├── pom.xml │ └── src │ │ └── main │ │ ├── java │ │ └── cn │ │ │ └── kiiwii │ │ │ └── framework │ │ │ ├── Application.java │ │ │ └── controller │ │ │ └── UserController.java │ │ └── resources │ │ ├── application-dev.properties │ │ ├── application-test.properties │ │ ├── application.properties │ │ └── log4j.properties ├── dobbo-interface │ ├── pom.xml │ └── src │ │ └── main │ │ └── java │ │ └── cn │ │ └── kiiwii │ │ └── framework │ │ └── dubbo │ │ └── api │ │ └── IPerson.java ├── dobbo-provider │ ├── pom.xml │ └── src │ │ └── main │ │ ├── java │ │ └── cn │ │ │ └── kiiwii │ │ │ └── framework │ │ │ └── dubbo │ │ │ └── provider │ │ │ ├── Application.java │ │ │ ├── dao │ │ │ ├── ITestDAO.java │ │ │ └── impl │ │ │ │ └── TestDAOImpl.java │ │ │ ├── druid │ │ │ ├── DruidConfiguration.java │ │ │ └── DruidDataSourceProperties.java │ │ │ └── service │ │ │ └── PersonServiceImpl.java │ │ └── resources │ │ ├── application.properties │ │ └── log4j.properties └── pom.xml ├── spring-boot-with-dynamic-datasource ├── pom.xml └── src │ └── main │ ├── java │ └── cn │ │ └── kiiwii │ │ └── framework │ │ ├── Application.java │ │ ├── controller │ │ └── TestController.java │ │ ├── dao │ │ ├── ITestDAO.java │ │ └── impl │ │ │ └── TestDAOImpl.java │ │ ├── druid │ │ ├── DruidConfiguration.java │ │ └── DynamicDataSource │ │ │ ├── DynamicDataSource.java │ │ │ ├── DynamicDataSourceAspect.java │ │ │ ├── DynamicDataSourceContextHolder.java │ │ │ ├── DynamicDataSourceRegister.java │ │ │ ├── MProxyTransactionManagementConfiguration.java │ │ │ ├── MTransactionInterceptor.java │ │ │ └── TargetDataSource.java │ │ └── service │ │ ├── ITestService.java │ │ └── impl │ │ └── TestServiceImpl.java │ ├── resources │ ├── application.properties │ └── log4j.properties │ └── script │ └── test.sql ├── spring-boot-with-freemarker ├── pom.xml └── src │ └── main │ ├── java │ └── cn │ │ └── kiiwii │ │ └── framework │ │ └── freemarker │ │ ├── Application.java │ │ ├── controller │ │ ├── ApiController.java │ │ └── WebController.java │ │ ├── model │ │ └── User.java │ │ └── service │ │ ├── IApiService.java │ │ └── impl │ │ └── ApiServiceImpl.java │ └── resources │ ├── application-dev.properties │ ├── application-prod.properties │ ├── application-test.properties │ ├── application.properties │ ├── log4j.properties │ ├── static │ └── bootstrap │ │ ├── css │ │ ├── bootstrap-override.css │ │ ├── bootstrap.css │ │ └── bootstrap.min.css │ │ ├── fonts │ │ └── bootstrap │ │ │ ├── glyphicons-halflings-regular.eot │ │ │ ├── glyphicons-halflings-regular.svg │ │ │ ├── glyphicons-halflings-regular.ttf │ │ │ ├── glyphicons-halflings-regular.woff │ │ │ └── glyphicons-halflings-regular.woff2 │ │ └── js │ │ ├── bootstrap.js │ │ └── bootstrap.min.js │ └── templates │ └── index.html ├── spring-boot-with-hibernate ├── README.md ├── pom.xml └── src │ └── main │ ├── java │ └── cn │ │ └── kiiwii │ │ └── framework │ │ └── hibernate │ │ ├── Application.java │ │ ├── aop │ │ └── ServiceAop.java │ │ ├── conf │ │ ├── ApplicationConfiguration.java │ │ ├── DruidDataSourceProperties.java │ │ └── HibernatePropertes.java │ │ ├── controller │ │ └── TestController.java │ │ ├── dao │ │ ├── ITestDAO.java │ │ └── impl │ │ │ └── TestDAOImpl.java │ │ ├── model │ │ ├── SpringBootWithHinernateTest.java │ │ └── SpringBootWithHinernateTest2.java │ │ └── service │ │ ├── ITestService.java │ │ └── impl │ │ └── TestServiceImpl.java │ ├── resources │ ├── application.properties │ └── log4j.properties │ └── script │ └── init.sql ├── spring-boot-with-jpa ├── pom.xml └── src │ └── main │ ├── java │ └── cn │ │ └── kiiwii │ │ └── framework │ │ ├── Application.java │ │ ├── controller │ │ └── TestController.java │ │ ├── dao │ │ ├── ITestDAO.java │ │ └── TestRepository.java │ │ ├── druid │ │ └── DruidConfiguration.java │ │ └── model │ │ └── Test.java │ ├── resources │ ├── application.properties │ └── log4j.properties │ └── script │ └── test.sql ├── spring-boot-with-mybatis ├── README.md ├── pom.xml └── src │ ├── main │ ├── java │ │ └── cn │ │ │ └── kiiwii │ │ │ └── framework │ │ │ └── mybatis │ │ │ ├── Application.java │ │ │ ├── aop │ │ │ └── ServiceAop.java │ │ │ ├── controller │ │ │ └── TestController.java │ │ │ ├── druid │ │ │ └── DruidConfiguration.java │ │ │ ├── mapper │ │ │ ├── TestMapper.java │ │ │ └── TestXmlMapper.java │ │ │ ├── mapping │ │ │ └── UserMapper.xml │ │ │ ├── model │ │ │ └── Account.java │ │ │ └── service │ │ │ ├── ITestService.java │ │ │ ├── ITestXmlService.java │ │ │ └── impl │ │ │ ├── TestServiceImpl.java │ │ │ └── TestXmlServiceImpl.java │ ├── resources │ │ ├── application.properties │ │ └── log4j.properties │ └── script │ │ └── test.sql │ └── test │ └── java │ └── cn │ └── kiiwii │ └── framework │ └── mybatis │ └── TestServiceTest.java └── spring-boot-with-schedule ├── pom.xml └── src ├── main ├── java │ └── cn │ │ └── kiiwii │ │ └── framework │ │ ├── Application.java │ │ ├── controller │ │ └── TestController.java │ │ ├── dao │ │ ├── ITestDAO.java │ │ └── impl │ │ │ └── TestDAOImpl.java │ │ ├── druid │ │ └── DruidConfiguration.java │ │ ├── schedule │ │ └── Scheduling.java │ │ └── service │ │ ├── ITestService.java │ │ └── impl │ │ └── TestServiceImpl.java ├── resources │ ├── application.properties │ └── log4j.properties └── script │ └── test.sql └── test └── java └── cn └── kiiwii └── framework └── AppTest.java /README.md: -------------------------------------------------------------------------------- 1 | # spring-boot druid mybatis schedule dynamic-datasource jpa 2 | 3 | 本系列是spring-boot相关的一些列子,比如spring-boot集成druid,以及druid的动态数据源切换, 4 | spring-boot 集成mybatis,spring-boot集成定时器等等 5 | 6 | # 1、spring-boot集成druid数据库连接池 7 | 8 | 详情查看项目 [spring-boot-with-druid](spring-boot-with-druid/) 9 | 10 | # 2、spring-boot实现druid数据库连接池的动态数据源切换, 11 | 12 | 详情查看项目 [spring-boot-with-dynamic-datasource](spring-boot-with-dynamic-datasource/) 13 | 14 | # 3、spring-boot实现定时任务 15 | 16 | 详情查看项目 [spring-boot-with-schedule](spring-boot-with-schedule/) 17 | 18 | # 4、spring-boot集成mybatis 19 | 20 | 详情查看项目 [spring-boot-with-mybatis](spring-boot-with-mybatis/) 21 | 22 | # 5、spring-boot集成jpa 23 | 24 | 详情查看项目 [spring-boot-with-jpa](spring-boot-with-jpa/) 25 | 26 | # 6、spring-boot集成hibernate(dao继承HibernateDaoSupport) 27 | 28 | 详情查看项目 [spring-boot-with-hibernate](spring-boot-with-hibernate/) 29 | 30 | # 7、spring-boot集成dubbo,所有配置均使用application.properties 31 | 32 | 详情查看项目 [spring-boot-with-dubbo](spring-boot-with-dubbo/) -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | 5 | cn.kiiwii.framework 6 | spring-boot-sample 7 | 1.0-SNAPSHOT 8 | 9 | spring-boot-with-schedule 10 | spring-boot-with-hibernate 11 | spring-boot-with-dynamic-datasource 12 | spring-boot-with-druid 13 | spring-boot-with-dubbo 14 | spring-boot-with-jpa 15 | spring-boot-with-mybatis 16 | spring-boot-with-druid-dpcp 17 | spring-boot-dubbo-plugin 18 | spring-boot-with-freemarker 19 | 20 | pom 21 | 22 | 23 | org.springframework.boot 24 | spring-boot-starter-parent 25 | 1.4.0.RELEASE 26 | 27 | 28 | spring-boot-sample 29 | http://maven.apache.org 30 | 31 | 32 | UTF-8 33 | 34 | 35 | 36 | 37 | junit 38 | junit 39 | 4.12 40 | test 41 | 42 | 43 | 44 | 45 | -------------------------------------------------------------------------------- /spring-boot-dubbo-plugin/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | spring-boot-sample 7 | cn.kiiwii.framework 8 | 1.0-SNAPSHOT 9 | 10 | 4.0.0 11 | 12 | 1.0.0-RELEASE 13 | spring-boot-dubbo-plugin 14 | 15 | 16 | 17 | org.springframework.boot 18 | spring-boot 19 | 1.4.0.RELEASE 20 | 21 | 22 | org.springframework.boot 23 | spring-boot-configuration-processor 24 | true 25 | 26 | 27 | org.springframework.boot 28 | spring-boot-autoconfigure 29 | 1.4.0.RELEASE 30 | 31 | 32 | org.apache.zookeeper 33 | zookeeper 34 | 3.4.8 35 | 36 | 37 | com.101tec 38 | zkclient 39 | 0.9 40 | 41 | 42 | com.alibaba 43 | dubbo 44 | 2.8.4 45 | 46 | 47 | org.jboss.netty 48 | netty 49 | 50 | 51 | spring 52 | org.springframework 53 | 54 | 55 | 56 | 57 | 58 | -------------------------------------------------------------------------------- /spring-boot-dubbo-plugin/src/main/java/cn/kiiwii/framework/dubbo/AnnotationBeanConfiguration.java: -------------------------------------------------------------------------------- 1 | package cn.kiiwii.framework.dubbo; 2 | 3 | import com.alibaba.dubbo.config.spring.AnnotationBean; 4 | import org.springframework.beans.factory.annotation.Value; 5 | import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; 6 | import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass; 7 | import org.springframework.context.annotation.Bean; 8 | import org.springframework.context.annotation.Configuration; 9 | import org.springframework.context.annotation.PropertySource; 10 | 11 | /** 12 | * Created by zhong on 2017/3/13. 13 | */ 14 | @Configuration 15 | @ConditionalOnMissingClass 16 | @PropertySource(value = "classpath:/application.properties") 17 | public class AnnotationBeanConfiguration { 18 | 19 | @Bean 20 | @ConditionalOnMissingBean 21 | public AnnotationBean annotationBean(@Value("${dubbo.annotation.package-name}") String packageName) { 22 | AnnotationBean annotationBean = new AnnotationBean(); 23 | annotationBean.setPackage(packageName); 24 | return annotationBean; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /spring-boot-dubbo-plugin/src/main/java/cn/kiiwii/framework/dubbo/consumer/DubboComsumerConfiguration.java: -------------------------------------------------------------------------------- 1 | package cn.kiiwii.framework.dubbo.consumer; 2 | 3 | import cn.kiiwii.framework.dubbo.DubboProperties; 4 | import com.alibaba.dubbo.config.ApplicationConfig; 5 | import com.alibaba.dubbo.config.ConsumerConfig; 6 | import com.alibaba.dubbo.config.RegistryConfig; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; 9 | import org.springframework.boot.context.properties.EnableConfigurationProperties; 10 | import org.springframework.context.annotation.Bean; 11 | import org.springframework.context.annotation.Configuration; 12 | 13 | /** 14 | * Created by zhong on 2016/11/22. 15 | */ 16 | @Configuration 17 | @EnableConfigurationProperties({DubboProperties.class}) 18 | public class DubboComsumerConfiguration { 19 | 20 | @Autowired 21 | private DubboProperties dubboProperties; 22 | 23 | /** 24 | * 注入dubbo上下文 25 | * 26 | * @return 27 | */ 28 | @Bean 29 | @ConditionalOnMissingBean 30 | public ApplicationConfig applicationConfig(RegistryConfig registryConfig) { 31 | // 当前应用配置 32 | ApplicationConfig applicationConfig = new ApplicationConfig(); 33 | applicationConfig.setName(dubboProperties.getApplication().getName()); 34 | applicationConfig.setVersion(dubboProperties.getApplication().getVersion()); 35 | applicationConfig.setArchitecture(dubboProperties.getApplication().getArchitecture()); 36 | applicationConfig.setCompiler(dubboProperties.getApplication().getCompiler()); 37 | applicationConfig.setDefault(dubboProperties.getApplication().getDefault()); 38 | applicationConfig.setEnvironment(dubboProperties.getApplication().getEnvironment()); 39 | applicationConfig.setLogger(dubboProperties.getApplication().getLogger()); 40 | applicationConfig.setMonitor(dubboProperties.getApplication().getArchitecture()); 41 | applicationConfig.setOrganization(dubboProperties.getApplication().getOrganization()); 42 | applicationConfig.setOwner(dubboProperties.getApplication().getOwner()); 43 | applicationConfig.setRegistry(registryConfig); 44 | return applicationConfig; 45 | } 46 | 47 | /** 48 | * 注入dubbo注册中心配置,基于zookeeper 49 | * 50 | * @return 51 | */ 52 | @Bean 53 | @ConditionalOnMissingBean 54 | public RegistryConfig registryConfig() { 55 | // 连接注册中心配置 56 | RegistryConfig registry = new RegistryConfig(); 57 | registry.setProtocol(dubboProperties.getRegistry().getProtocol()); 58 | registry.setAddress(dubboProperties.getRegistry().getAddress()); 59 | registry.setVersion(dubboProperties.getRegistry().getVersion()); 60 | registry.setUsername(dubboProperties.getRegistry().getUsername()); 61 | registry.setPassword(dubboProperties.getRegistry().getPassword()); 62 | registry.setGroup(dubboProperties.getRegistry().getGroup()); 63 | registry.setCheck(dubboProperties.getRegistry().getCheck()); 64 | registry.setClient(dubboProperties.getRegistry().getClient()); 65 | registry.setCluster(dubboProperties.getRegistry().getCluster()); 66 | registry.setDefault(dubboProperties.getRegistry().getDefault()); 67 | registry.setDynamic(dubboProperties.getRegistry().getDynamic()); 68 | registry.setFile(dubboProperties.getRegistry().getFile()); 69 | registry.setPort(dubboProperties.getRegistry().getPort()); 70 | registry.setRegister(dubboProperties.getRegistry().getRegister()); 71 | registry.setServer(dubboProperties.getRegistry().getServer()); 72 | registry.setSubscribe(dubboProperties.getRegistry().getSubscribe()); 73 | registry.setTimeout(dubboProperties.getRegistry().getTimeout()); 74 | registry.setTransporter(dubboProperties.getRegistry().getTransporter()); 75 | return registry; 76 | } 77 | 78 | /** 79 | * dubbo消费 80 | * 81 | * @param applicationConfig 82 | * @param registryConfig 83 | * @return 84 | */ 85 | @Bean(name="defaultConsumer") 86 | @ConditionalOnMissingBean 87 | public ConsumerConfig consumerConfig(ApplicationConfig applicationConfig, RegistryConfig registryConfig) { 88 | ConsumerConfig consumerConfig = new ConsumerConfig(); 89 | consumerConfig.setApplication(applicationConfig); 90 | consumerConfig.setRegistry(registryConfig); 91 | consumerConfig.setOwner(dubboProperties.getConsumer().getOwner()); 92 | consumerConfig.setMonitor(dubboProperties.getConsumer().getMonitor()); 93 | consumerConfig.setDefault(dubboProperties.getConsumer().getDefault()); 94 | consumerConfig.setTimeout(dubboProperties.getConsumer().getTimeout()); 95 | consumerConfig.setActives(dubboProperties.getConsumer().getActives()); 96 | consumerConfig.setAsync(dubboProperties.getConsumer().getAsync()); 97 | consumerConfig.setCache(dubboProperties.getConsumer().getCache()); 98 | consumerConfig.setCallbacks(dubboProperties.getConsumer().getCallbacks()); 99 | consumerConfig.setCheck(dubboProperties.getConsumer().getCheck()); 100 | consumerConfig.setCluster(dubboProperties.getConsumer().getCluster()); 101 | consumerConfig.setConnections(dubboProperties.getConsumer().getConnections()); 102 | consumerConfig.setFilter(dubboProperties.getConsumer().getFilter()); 103 | consumerConfig.setGeneric(dubboProperties.getConsumer().getGeneric()); 104 | consumerConfig.setGroup(dubboProperties.getConsumer().getGroup()); 105 | consumerConfig.setVersion(dubboProperties.getConsumer().getVersion()); 106 | return consumerConfig; 107 | } 108 | } 109 | -------------------------------------------------------------------------------- /spring-boot-dubbo-plugin/src/main/java/cn/kiiwii/framework/dubbo/provider/DubboProviderConfiguration.java: -------------------------------------------------------------------------------- 1 | package cn.kiiwii.framework.dubbo.provider; 2 | 3 | import cn.kiiwii.framework.dubbo.DubboProperties; 4 | import com.alibaba.dubbo.config.*; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; 7 | import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass; 8 | import org.springframework.boot.context.properties.EnableConfigurationProperties; 9 | import org.springframework.context.annotation.Bean; 10 | import org.springframework.context.annotation.Configuration; 11 | import org.springframework.core.annotation.Order; 12 | 13 | /** 14 | * Created by zhong on 2016/11/22. 15 | */ 16 | @Configuration 17 | @EnableConfigurationProperties({DubboProperties.class}) 18 | @ConditionalOnMissingClass 19 | @Order(value = -1) 20 | public class DubboProviderConfiguration { 21 | 22 | @Autowired 23 | private DubboProperties dubboProperties; 24 | 25 | /** 26 | * 注入dubbo注册中心配置,基于zookeeper 27 | * @return 28 | */ 29 | @Bean 30 | @ConditionalOnMissingBean 31 | public RegistryConfig registryConfig() { 32 | // 连接注册中心配置 33 | RegistryConfig registry = new RegistryConfig(); 34 | registry.setProtocol(dubboProperties.getRegistry().getProtocol()); 35 | registry.setAddress(dubboProperties.getRegistry().getAddress()); 36 | registry.setVersion(dubboProperties.getRegistry().getVersion()); 37 | registry.setUsername(dubboProperties.getRegistry().getUsername()); 38 | registry.setPassword(dubboProperties.getRegistry().getPassword()); 39 | registry.setGroup(dubboProperties.getRegistry().getGroup()); 40 | registry.setCheck(dubboProperties.getRegistry().getCheck()); 41 | registry.setClient(dubboProperties.getRegistry().getClient()); 42 | registry.setCluster(dubboProperties.getRegistry().getCluster()); 43 | registry.setDefault(dubboProperties.getRegistry().getDefault()); 44 | registry.setDynamic(dubboProperties.getRegistry().getDynamic()); 45 | registry.setFile(dubboProperties.getRegistry().getFile()); 46 | registry.setPort(dubboProperties.getRegistry().getPort()); 47 | registry.setRegister(dubboProperties.getRegistry().getRegister()); 48 | registry.setServer(dubboProperties.getRegistry().getServer()); 49 | registry.setSubscribe(dubboProperties.getRegistry().getSubscribe()); 50 | registry.setTimeout(dubboProperties.getRegistry().getTimeout()); 51 | registry.setTransporter(dubboProperties.getRegistry().getTransporter()); 52 | return registry; 53 | } 54 | 55 | /* * 56 | * 注入dubbo上下文 57 | * 58 | * @return 59 | */ 60 | @Bean 61 | @ConditionalOnMissingBean 62 | public ApplicationConfig applicationConfig(RegistryConfig registryConfig) { 63 | // 当前应用配置 64 | ApplicationConfig applicationConfig = new ApplicationConfig(); 65 | applicationConfig.setName(dubboProperties.getApplication().getName()); 66 | applicationConfig.setVersion(dubboProperties.getApplication().getVersion()); 67 | applicationConfig.setArchitecture(dubboProperties.getApplication().getArchitecture()); 68 | applicationConfig.setCompiler(dubboProperties.getApplication().getCompiler()); 69 | applicationConfig.setDefault(dubboProperties.getApplication().getDefault()); 70 | applicationConfig.setEnvironment(dubboProperties.getApplication().getEnvironment()); 71 | applicationConfig.setLogger(dubboProperties.getApplication().getLogger()); 72 | applicationConfig.setMonitor(dubboProperties.getApplication().getArchitecture()); 73 | applicationConfig.setOrganization(dubboProperties.getApplication().getOrganization()); 74 | applicationConfig.setOwner(dubboProperties.getApplication().getOwner()); 75 | applicationConfig.setRegistry(registryConfig); 76 | return applicationConfig; 77 | } 78 | 79 | /* * 80 | * 默认基于dubbo协议提供服务 81 | * 82 | * @return 83 | 84 | */ 85 | @Bean 86 | @ConditionalOnMissingBean 87 | public ProtocolConfig protocolConfig() { 88 | // 服务提供者协议配置 89 | ProtocolConfig protocolConfig = new ProtocolConfig(); 90 | protocolConfig.setName(dubboProperties.getProtocol().getName()); 91 | protocolConfig.setPort(dubboProperties.getProtocol().getPort()); 92 | protocolConfig.setAccepts(dubboProperties.getProtocol().getAccepts()); 93 | protocolConfig.setAccesslog(dubboProperties.getProtocol().getAccesslog()); 94 | protocolConfig.setBuffer(dubboProperties.getProtocol().getBuffer()); 95 | protocolConfig.setCharset(dubboProperties.getProtocol().getCharset()); 96 | protocolConfig.setClient(dubboProperties.getProtocol().getClient()); 97 | protocolConfig.setCodec(dubboProperties.getProtocol().getCodec()); 98 | protocolConfig.setContextpath(dubboProperties.getProtocol().getContextpath()); 99 | protocolConfig.setDefault(dubboProperties.getProtocol().getDefault()); 100 | protocolConfig.setDispatcher(dubboProperties.getProtocol().getDispatcher()); 101 | protocolConfig.setExchanger(dubboProperties.getProtocol().getExchanger()); 102 | protocolConfig.setExtension(dubboProperties.getProtocol().getExtension()); 103 | protocolConfig.setHeartbeat(dubboProperties.getProtocol().getHeartbeat()); 104 | protocolConfig.setHost(dubboProperties.getProtocol().getHost()); 105 | protocolConfig.setIothreads(dubboProperties.getProtocol().getIothreads()); 106 | protocolConfig.setKeepAlive(dubboProperties.getProtocol().getKeepAlive()); 107 | protocolConfig.setNetworker(dubboProperties.getProtocol().getNetworker()); 108 | protocolConfig.setOptimizer(dubboProperties.getProtocol().getOptimizer()); 109 | protocolConfig.setPayload(dubboProperties.getProtocol().getPayload()); 110 | protocolConfig.setPrompt(dubboProperties.getProtocol().getPrompt()); 111 | protocolConfig.setQueues(dubboProperties.getProtocol().getQueues()); 112 | protocolConfig.setRegister(dubboProperties.getProtocol().getRegister()); 113 | protocolConfig.setSerialization(dubboProperties.getProtocol().getSerialization()); 114 | protocolConfig.setServer(dubboProperties.getProtocol().getServer()); 115 | protocolConfig.setStatus(dubboProperties.getProtocol().getStatus()); 116 | protocolConfig.setTelnet(dubboProperties.getProtocol().getTelnet()); 117 | protocolConfig.setThreadpool(dubboProperties.getProtocol().getThreadpool()); 118 | protocolConfig.setThreads(dubboProperties.getProtocol().getThreads()); 119 | protocolConfig.setTransporter(dubboProperties.getProtocol().getTransporter()); 120 | return protocolConfig; 121 | } 122 | 123 | /* * 124 | * dubbo服务提供 125 | * 126 | * @param applicationConfig 127 | * @param registryConfig 128 | * @param protocolConfig 129 | * @return 130 | 131 | */ 132 | @Bean 133 | @ConditionalOnMissingBean 134 | public ProviderConfig providerConfig(ApplicationConfig applicationConfig, RegistryConfig registryConfig, ProtocolConfig protocolConfig) { 135 | ProviderConfig providerConfig = new ProviderConfig(); 136 | providerConfig.setTimeout(3000); 137 | providerConfig.setRetries(3); 138 | providerConfig.setDelay(300); 139 | providerConfig.setApplication(applicationConfig); 140 | providerConfig.setRegistry(registryConfig); 141 | providerConfig.setProtocol(protocolConfig); 142 | return providerConfig; 143 | } 144 | 145 | @Bean 146 | @ConditionalOnMissingBean 147 | public MonitorConfig monitorConfig() { 148 | MonitorConfig monitorConfig = new MonitorConfig(); 149 | monitorConfig.setAddress(dubboProperties.getMonitor().getAddress()); 150 | monitorConfig.setGroup(dubboProperties.getMonitor().getGroup()); 151 | monitorConfig.setPassword(dubboProperties.getMonitor().getPassword()); 152 | monitorConfig.setProtocol(dubboProperties.getMonitor().getProtocol()); 153 | monitorConfig.setUsername(dubboProperties.getMonitor().getUsername()); 154 | monitorConfig.setVersion(dubboProperties.getMonitor().getVersion()); 155 | monitorConfig.setDefault(dubboProperties.getMonitor().getDefault()); 156 | return monitorConfig; 157 | } 158 | } 159 | -------------------------------------------------------------------------------- /spring-boot-with-druid/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | spring-boot-sample 7 | cn.kiiwii.framework 8 | 1.0-SNAPSHOT 9 | 10 | 4.0.0 11 | 12 | spring-boot-with-druid 13 | 14 | 15 | 16 | junit 17 | junit 18 | 4.12 19 | test 20 | 21 | 22 | org.springframework.boot 23 | spring-boot-starter-web 24 | 25 | 26 | org.springframework.boot 27 | spring-boot-starter 28 | 29 | 30 | org.springframework.boot 31 | spring-boot-starter-logging 32 | 33 | 34 | 35 | 36 | org.springframework.boot 37 | spring-boot-configuration-processor 38 | true 39 | 40 | 41 | org.springframework.boot 42 | spring-boot-starter-jdbc 43 | 44 | 45 | org.springframework.boot 46 | spring-boot-starter-log4j 47 | 1.3.7.RELEASE 48 | 49 | 50 | org.springframework.boot 51 | spring-boot-starter-aop 52 | 53 | 54 | mysql 55 | mysql-connector-java 56 | 5.1.38 57 | 58 | 59 | com.alibaba 60 | druid 61 | 1.0.25 62 | 63 | 64 | org.springframework 65 | spring-context 66 | 4.3.2.RELEASE 67 | 68 | 69 | org.springframework 70 | spring-orm 71 | 4.3.2.RELEASE 72 | 73 | 74 | 75 | 76 | 77 | 78 | org.apache.maven.plugins 79 | maven-compiler-plugin 80 | 3.2 81 | 82 | 1.7 83 | 1.7 84 | 85 | 86 | 87 | org.springframework.boot 88 | spring-boot-maven-plugin 89 | 90 | 91 | 92 | repackage 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | -------------------------------------------------------------------------------- /spring-boot-with-druid/src/main/java/cn/kiiwii/framework/Application.java: -------------------------------------------------------------------------------- 1 | package cn.kiiwii.framework; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | import org.springframework.boot.SpringApplication; 6 | import org.springframework.boot.autoconfigure.EnableAutoConfiguration; 7 | import org.springframework.boot.autoconfigure.ImportAutoConfiguration; 8 | import org.springframework.boot.autoconfigure.SpringBootApplication; 9 | import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; 10 | import org.springframework.boot.builder.SpringApplicationBuilder; 11 | import org.springframework.boot.context.properties.EnableConfigurationProperties; 12 | import org.springframework.boot.web.support.SpringBootServletInitializer; 13 | import org.springframework.context.annotation.Bean; 14 | import org.springframework.context.annotation.Configuration; 15 | import org.springframework.jdbc.datasource.DataSourceTransactionManager; 16 | import org.springframework.transaction.PlatformTransactionManager; 17 | import org.springframework.transaction.annotation.EnableTransactionManagement; 18 | import org.springframework.web.bind.annotation.RestController; 19 | 20 | import javax.sql.DataSource; 21 | 22 | /** 23 | * Created by zhong on 2016/11/10. 24 | */ 25 | @RestController 26 | @SpringBootApplication 27 | @EnableAutoConfiguration 28 | @ImportAutoConfiguration 29 | @EnableTransactionManagement 30 | @EnableConfigurationProperties 31 | @Configuration 32 | public class Application extends SpringBootServletInitializer { 33 | 34 | static Logger logger = LoggerFactory.getLogger(Application.class); 35 | 36 | @Bean 37 | @ConditionalOnMissingBean 38 | public PlatformTransactionManager txManager(DataSource dataSource){ 39 | return new DataSourceTransactionManager(dataSource); 40 | } 41 | 42 | @Override 43 | protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { 44 | return application.sources(Application.class); 45 | } 46 | 47 | public static void main(String[] args) throws Exception { 48 | SpringApplication.run(Application.class, args); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /spring-boot-with-druid/src/main/java/cn/kiiwii/framework/aop/ServiceAop.java: -------------------------------------------------------------------------------- 1 | package cn.kiiwii.framework.aop; 2 | 3 | import org.aspectj.lang.JoinPoint; 4 | import org.aspectj.lang.ProceedingJoinPoint; 5 | import org.aspectj.lang.annotation.*; 6 | import org.slf4j.Logger; 7 | import org.slf4j.LoggerFactory; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.stereotype.Component; 10 | import org.springframework.web.context.request.RequestContextHolder; 11 | import org.springframework.web.context.request.ServletRequestAttributes; 12 | import org.springframework.web.servlet.HandlerMapping; 13 | 14 | import javax.servlet.http.HttpServletRequest; 15 | import java.util.Map; 16 | 17 | /** 18 | * Created by zhong on 2016/11/24. 19 | */ 20 | @Aspect 21 | @Component 22 | public class ServiceAop { 23 | private static Logger logger = LoggerFactory.getLogger(ServiceAop.class); 24 | 25 | /* private ThreadLocal tlocal = new ThreadLocal(); 26 | 27 | @Autowired 28 | private OptLogService optLogService;*/ 29 | 30 | @Pointcut("execution(public * cn.kiiwii.framework.service.impl.*.*(..))") 31 | public void webRequestLog() {} 32 | 33 | @Before("webRequestLog()") 34 | public void doBefore(JoinPoint joinPoint) { 35 | ThreadLocal threadLocal; 36 | ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); 37 | HttpServletRequest request = attributes.getRequest(); 38 | String beanName = joinPoint.getSignature().getDeclaringTypeName(); 39 | String methodName = joinPoint.getSignature().getName(); 40 | String uri = request.getRequestURI(); 41 | String remoteAddr = getIpAddr(request); 42 | String sessionId = request.getSession().getId(); 43 | String user = (String) request.getSession().getAttribute("user"); 44 | String method = request.getMethod(); 45 | String params = ""; 46 | /*try { 47 | 48 | long beginTime = System.currentTimeMillis(); 49 | 50 | // 接收到请求,记录请求内容 51 | ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); 52 | HttpServletRequest request = attributes.getRequest(); 53 | String beanName = joinPoint.getSignature().getDeclaringTypeName(); 54 | String methodName = joinPoint.getSignature().getName(); 55 | String uri = request.getRequestURI(); 56 | String remoteAddr = getIpAddr(request); 57 | String sessionId = request.getSession().getId(); 58 | String user = (String) request.getSession().getAttribute("user"); 59 | String method = request.getMethod(); 60 | String params = ""; 61 | if ("POST".equals(method)) { 62 | Object[] paramsArray = joinPoint.getArgs(); 63 | params = argsArrayToString(paramsArray); 64 | } else { 65 | Map paramsMap = (Map) request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE); 66 | params = paramsMap.toString(); 67 | } 68 | 69 | logger.debug("uri=" + uri + "; beanName=" + beanName + "; remoteAddr=" + remoteAddr + "; user=" + user 70 | + "; methodName=" + methodName + "; params=" + params); 71 | 72 | OperatorLog optLog = new OperatorLog(); 73 | optLog.setBeanName(beanName); 74 | optLog.setCurUser(user); 75 | optLog.setMethodName(methodName); 76 | optLog.setParams(params != null ? params.toString() : ""); 77 | optLog.setRemoteAddr(remoteAddr); 78 | optLog.setSessionId(sessionId); 79 | optLog.setUri(uri); 80 | optLog.setRequestTime(beginTime); 81 | tlocal.set(optLog); 82 | 83 | } catch (Exception e) { 84 | logger.error("***操作请求日志记录失败doBefore()***", e); 85 | }*/ 86 | } 87 | 88 | @AfterReturning(returning = "result", pointcut = "webRequestLog()") 89 | public void doAfterReturning(Object result) { 90 | /*try { 91 | // 处理完请求,返回内容 92 | OperatorLog optLog = tlocal.get(); 93 | optLog.setResult(result.toString()); 94 | long beginTime = optLog.getRequestTime(); 95 | long requestTime = (System.currentTimeMillis() - beginTime) / 1000; 96 | optLog.setRequestTime(requestTime); 97 | 98 | System.out.println("请求耗时:" + requestTime + optLog.getUri() + " ** " + optLog.getParams() + " ** " 99 | + optLog.getMethodName()); 100 | System.out.println("RESPONSE : " + result); 101 | 102 | optLogService.saveLog(optLog); 103 | } catch (Exception e) { 104 | logger.error("***操作请求日志记录失败doAfterReturning()***", e); 105 | }*/ 106 | } 107 | 108 | @Around("webRequestLog()") 109 | public Object around(ProceedingJoinPoint pjp) throws Throwable { 110 | System.out.println("方法环绕start....."); 111 | Object o = null; 112 | System.out.println("before---------------------"); 113 | o = pjp.proceed(); 114 | System.out.println("after---------------------"); 115 | return o; 116 | } 117 | 118 | /** 119 | * 获取登录用户远程主机ip地址 120 | * 121 | * @param request 122 | * @return 123 | */ 124 | private String getIpAddr(HttpServletRequest request) { 125 | String ip = request.getHeader("x-forwarded-for"); 126 | if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 127 | ip = request.getHeader("Proxy-Client-IP"); 128 | } 129 | if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 130 | ip = request.getHeader("WL-Proxy-Client-IP"); 131 | } 132 | if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 133 | ip = request.getRemoteAddr(); 134 | } 135 | return ip; 136 | } 137 | 138 | /** 139 | * 请求参数拼装 140 | * 141 | * @param paramsArray 142 | * @return 143 | */ 144 | private String argsArrayToString(Object[] paramsArray) { 145 | String params = ""; 146 | if (paramsArray != null && paramsArray.length > 0) { 147 | for (int i = 0; i < paramsArray.length; i++) { 148 | Object jsonObj = paramsArray[i]; 149 | params += jsonObj.toString() + " "; 150 | } 151 | } 152 | return params.trim(); 153 | } 154 | } 155 | -------------------------------------------------------------------------------- /spring-boot-with-druid/src/main/java/cn/kiiwii/framework/aop/WebAspect.java: -------------------------------------------------------------------------------- 1 | package cn.kiiwii.framework.aop; 2 | 3 | import org.aspectj.lang.JoinPoint; 4 | import org.aspectj.lang.ProceedingJoinPoint; 5 | import org.aspectj.lang.annotation.*; 6 | import org.slf4j.Logger; 7 | import org.slf4j.LoggerFactory; 8 | import org.springframework.stereotype.Component; 9 | import org.springframework.web.context.request.RequestContextHolder; 10 | import org.springframework.web.context.request.ServletRequestAttributes; 11 | 12 | import javax.servlet.http.HttpServletRequest; 13 | 14 | /** 15 | * Created by zhong on 2016/11/24. 16 | */ 17 | @Aspect 18 | @Component 19 | public class WebAspect { 20 | private static Logger logger = LoggerFactory.getLogger(WebAspect.class); 21 | 22 | @Pointcut("execution(public * cn.kiiwii.framework.controller.*.*(..))") 23 | public void webAspect() { 24 | } 25 | 26 | @Before("webAspect()") 27 | public void doBefore(JoinPoint joinPoint) { 28 | ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); 29 | HttpServletRequest request = attributes.getRequest(); 30 | String beanName = joinPoint.getSignature().getDeclaringTypeName(); 31 | String methodName = joinPoint.getSignature().getName(); 32 | String uri = request.getRequestURI(); 33 | String remoteAddr = getIpAddr(request); 34 | String sessionId = request.getSession().getId(); 35 | String user = (String) request.getSession().getAttribute("user"); 36 | String method = request.getMethod(); 37 | String params = ""; 38 | System.out.println(sessionId); 39 | } 40 | 41 | @AfterReturning(returning = "result", pointcut = "webAspect()") 42 | public void doAfterReturning(Object result) { 43 | } 44 | 45 | @Around("webAspect()") 46 | public Object around(ProceedingJoinPoint pjp) throws Throwable { 47 | System.out.println("方法环绕start....."); 48 | Object o = null; 49 | System.out.println("before---------------------"); 50 | o = pjp.proceed(); 51 | System.out.println("after---------------------"); 52 | return o; 53 | } 54 | 55 | /** 56 | * 获取登录用户远程主机ip地址 57 | * 58 | * @param request 59 | * @return 60 | */ 61 | private String getIpAddr(HttpServletRequest request) { 62 | String ip = request.getHeader("x-forwarded-for"); 63 | if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 64 | ip = request.getHeader("Proxy-Client-IP"); 65 | } 66 | if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 67 | ip = request.getHeader("WL-Proxy-Client-IP"); 68 | } 69 | if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 70 | ip = request.getRemoteAddr(); 71 | } 72 | return ip; 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /spring-boot-with-druid/src/main/java/cn/kiiwii/framework/controller/TestController.java: -------------------------------------------------------------------------------- 1 | package cn.kiiwii.framework.controller; 2 | 3 | import cn.kiiwii.framework.service.ITestService; 4 | import org.slf4j.Logger; 5 | import org.slf4j.LoggerFactory; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.stereotype.Controller; 8 | import org.springframework.web.bind.annotation.RequestMapping; 9 | import org.springframework.web.bind.annotation.RestController; 10 | 11 | /** 12 | * Created by zhong on 2016/11/10. 13 | */ 14 | @RestController 15 | @Controller 16 | public class TestController { 17 | @Autowired 18 | private ITestService testService; 19 | private Logger logger = LoggerFactory.getLogger(this.getClass()); 20 | 21 | @RequestMapping("/test") 22 | public String greeting() { 23 | testService.test(); 24 | return "hello"; 25 | } 26 | 27 | @RequestMapping("/testTrans") 28 | public String testTrans() { 29 | try { 30 | testService.testTransaction(); 31 | } catch (Exception e) { 32 | e.printStackTrace(); 33 | } 34 | return "testTransaction"; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /spring-boot-with-druid/src/main/java/cn/kiiwii/framework/dao/ITestDAO.java: -------------------------------------------------------------------------------- 1 | package cn.kiiwii.framework.dao; 2 | 3 | /** 4 | * Created by zhong on 2016/9/5. 5 | */ 6 | public interface ITestDAO { 7 | void test(); 8 | 9 | void save(); 10 | } 11 | -------------------------------------------------------------------------------- /spring-boot-with-druid/src/main/java/cn/kiiwii/framework/dao/impl/TestDAOImpl.java: -------------------------------------------------------------------------------- 1 | package cn.kiiwii.framework.dao.impl; 2 | 3 | import cn.kiiwii.framework.dao.ITestDAO; 4 | import org.springframework.beans.factory.annotation.Autowired; 5 | import org.springframework.jdbc.core.JdbcTemplate; 6 | import org.springframework.stereotype.Repository; 7 | import org.springframework.transaction.annotation.Propagation; 8 | import org.springframework.transaction.annotation.Transactional; 9 | 10 | import java.util.List; 11 | import java.util.Map; 12 | 13 | /** 14 | * Created by zhong on 2016/9/5. 15 | */ 16 | @Repository("testDAO") 17 | public class TestDAOImpl implements ITestDAO { 18 | 19 | @Autowired 20 | private JdbcTemplate jdbcTemplate; 21 | @Override 22 | public void test() { 23 | List> list = this.jdbcTemplate.queryForList("select * from test"); 24 | System.out.println(list); 25 | } 26 | 27 | @Transactional(propagation = Propagation.REQUIRED) 28 | @Override 29 | public void save() { 30 | this.jdbcTemplate.execute("INSERT INTO test (`test_name`,`test_num`) VALUES ('zhong','27')"); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /spring-boot-with-druid/src/main/java/cn/kiiwii/framework/druid/DruidConfiguration.java: -------------------------------------------------------------------------------- 1 | package cn.kiiwii.framework.druid; 2 | 3 | import com.alibaba.druid.pool.DruidDataSource; 4 | import com.alibaba.druid.support.http.StatViewServlet; 5 | import com.alibaba.druid.support.http.WebStatFilter; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.beans.factory.annotation.Value; 8 | import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; 9 | import org.springframework.boot.context.properties.ConfigurationProperties; 10 | import org.springframework.boot.context.properties.EnableConfigurationProperties; 11 | import org.springframework.boot.web.servlet.FilterRegistrationBean; 12 | import org.springframework.boot.web.servlet.ServletRegistrationBean; 13 | import org.springframework.context.annotation.Bean; 14 | import org.springframework.context.annotation.Configuration; 15 | 16 | import javax.sql.DataSource; 17 | import java.sql.SQLException; 18 | 19 | /** 20 | * Created by zhong on 2016/9/5. 21 | */ 22 | @Configuration 23 | @EnableConfigurationProperties({DruidDataSourceProperties.class}) 24 | public class DruidConfiguration { 25 | 26 | @Autowired 27 | private DruidDataSourceProperties properties; 28 | 29 | @Bean 30 | @ConditionalOnMissingBean 31 | public DataSource druidDataSource() { 32 | DruidDataSource druidDataSource = new DruidDataSource(); 33 | druidDataSource.setDriverClassName(properties.getDriverClassName()); 34 | druidDataSource.setUrl(properties.getUrl()); 35 | druidDataSource.setUsername(properties.getUsername()); 36 | druidDataSource.setPassword(properties.getPassword()); 37 | druidDataSource.setInitialSize(properties.getInitialSize()); 38 | druidDataSource.setMinIdle(properties.getMinIdle()); 39 | druidDataSource.setMaxActive(properties.getMaxActive()); 40 | druidDataSource.setMaxWait(properties.getMaxWait()); 41 | druidDataSource.setTimeBetweenEvictionRunsMillis(properties.getTimeBetweenEvictionRunsMillis()); 42 | druidDataSource.setMinEvictableIdleTimeMillis(properties.getMinEvictableIdleTimeMillis()); 43 | druidDataSource.setValidationQuery(properties.getValidationQuery()); 44 | druidDataSource.setTestWhileIdle(properties.isTestWhileIdle()); 45 | druidDataSource.setTestOnBorrow(properties.isTestOnBorrow()); 46 | druidDataSource.setTestOnReturn(properties.isTestOnReturn()); 47 | druidDataSource.setPoolPreparedStatements(properties.isPoolPreparedStatements()); 48 | druidDataSource.setMaxPoolPreparedStatementPerConnectionSize(properties.getMaxPoolPreparedStatementPerConnectionSize()); 49 | druidDataSource.setConnectionProperties(properties.getConnectionProperties()); 50 | try { 51 | druidDataSource.setFilters(properties.getFilters()); 52 | druidDataSource.init(); 53 | } catch (SQLException e) { 54 | e.printStackTrace(); 55 | } 56 | 57 | return druidDataSource; 58 | } 59 | 60 | @Bean 61 | @ConditionalOnMissingBean 62 | public ServletRegistrationBean druidServlet() { 63 | 64 | ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*"); 65 | 66 | //添加初始化参数:initParams 67 | 68 | //白名单: 69 | //servletRegistrationBean.addInitParameter("allow","127.0.0.1"); 70 | //IP黑名单 (存在共同时,deny优先于allow) : 如果满足deny的话提示:Sorry, you are not permitted to view this page. 71 | //servletRegistrationBean.addInitParameter("deny","192.168.1.73"); 72 | //登录查看信息的账号密码. 73 | servletRegistrationBean.addInitParameter("loginUsername", "admin"); 74 | servletRegistrationBean.addInitParameter("loginPassword", "admin"); 75 | //是否能够重置数据. 76 | servletRegistrationBean.addInitParameter("resetEnable", "true"); 77 | return servletRegistrationBean; 78 | 79 | } 80 | 81 | @Bean 82 | @ConditionalOnMissingBean 83 | public FilterRegistrationBean filterRegistrationBean() { 84 | FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(); 85 | filterRegistrationBean.setFilter(new WebStatFilter()); 86 | filterRegistrationBean.addUrlPatterns("/*"); 87 | filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*"); 88 | return filterRegistrationBean; 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /spring-boot-with-druid/src/main/java/cn/kiiwii/framework/druid/DruidDataSourceProperties.java: -------------------------------------------------------------------------------- 1 | package cn.kiiwii.framework.druid; 2 | 3 | import org.springframework.boot.context.properties.ConfigurationProperties; 4 | 5 | /** 6 | * Created by zhong on 2017/1/7. 7 | */ 8 | @ConfigurationProperties(prefix = "spring.datasource.druid") 9 | public class DruidDataSourceProperties { 10 | 11 | private String driverClassName; 12 | private String url; 13 | private String username; 14 | private String password; 15 | 16 | private int initialSize; 17 | private int minIdle; 18 | private int maxActive; 19 | private long maxWait; 20 | private long timeBetweenEvictionRunsMillis; 21 | private long minEvictableIdleTimeMillis; 22 | private String validationQuery; 23 | private boolean testWhileIdle; 24 | private boolean testOnBorrow; 25 | private boolean testOnReturn; 26 | private boolean poolPreparedStatements; 27 | private int maxPoolPreparedStatementPerConnectionSize; 28 | private String filters; 29 | private String connectionProperties; 30 | 31 | public int getInitialSize() { 32 | return initialSize; 33 | } 34 | 35 | public void setInitialSize(int initialSize) { 36 | this.initialSize = initialSize; 37 | } 38 | 39 | public int getMinIdle() { 40 | return minIdle; 41 | } 42 | 43 | public void setMinIdle(int minIdle) { 44 | this.minIdle = minIdle; 45 | } 46 | 47 | public int getMaxActive() { 48 | return maxActive; 49 | } 50 | 51 | public void setMaxActive(int maxActive) { 52 | this.maxActive = maxActive; 53 | } 54 | 55 | public long getMaxWait() { 56 | return maxWait; 57 | } 58 | 59 | public void setMaxWait(long maxWait) { 60 | this.maxWait = maxWait; 61 | } 62 | 63 | public long getTimeBetweenEvictionRunsMillis() { 64 | return timeBetweenEvictionRunsMillis; 65 | } 66 | 67 | public void setTimeBetweenEvictionRunsMillis(long timeBetweenEvictionRunsMillis) { 68 | this.timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis; 69 | } 70 | 71 | public long getMinEvictableIdleTimeMillis() { 72 | return minEvictableIdleTimeMillis; 73 | } 74 | 75 | public void setMinEvictableIdleTimeMillis(long minEvictableIdleTimeMillis) { 76 | this.minEvictableIdleTimeMillis = minEvictableIdleTimeMillis; 77 | } 78 | 79 | public String getValidationQuery() { 80 | return validationQuery; 81 | } 82 | 83 | public void setValidationQuery(String validationQuery) { 84 | this.validationQuery = validationQuery; 85 | } 86 | 87 | public boolean isTestWhileIdle() { 88 | return testWhileIdle; 89 | } 90 | 91 | public void setTestWhileIdle(boolean testWhileIdle) { 92 | this.testWhileIdle = testWhileIdle; 93 | } 94 | 95 | public boolean isTestOnBorrow() { 96 | return testOnBorrow; 97 | } 98 | 99 | public void setTestOnBorrow(boolean testOnBorrow) { 100 | this.testOnBorrow = testOnBorrow; 101 | } 102 | 103 | public boolean isTestOnReturn() { 104 | return testOnReturn; 105 | } 106 | 107 | public void setTestOnReturn(boolean testOnReturn) { 108 | this.testOnReturn = testOnReturn; 109 | } 110 | 111 | public boolean isPoolPreparedStatements() { 112 | return poolPreparedStatements; 113 | } 114 | 115 | public void setPoolPreparedStatements(boolean poolPreparedStatements) { 116 | this.poolPreparedStatements = poolPreparedStatements; 117 | } 118 | 119 | public int getMaxPoolPreparedStatementPerConnectionSize() { 120 | return maxPoolPreparedStatementPerConnectionSize; 121 | } 122 | 123 | public void setMaxPoolPreparedStatementPerConnectionSize(int maxPoolPreparedStatementPerConnectionSize) { 124 | this.maxPoolPreparedStatementPerConnectionSize = maxPoolPreparedStatementPerConnectionSize; 125 | } 126 | 127 | public String getFilters() { 128 | return filters; 129 | } 130 | 131 | public void setFilters(String filters) { 132 | this.filters = filters; 133 | } 134 | 135 | public String getConnectionProperties() { 136 | return connectionProperties; 137 | } 138 | 139 | public void setConnectionProperties(String connectionProperties) { 140 | this.connectionProperties = connectionProperties; 141 | } 142 | 143 | public String getDriverClassName() { 144 | return driverClassName; 145 | } 146 | 147 | public void setDriverClassName(String driverClassName) { 148 | this.driverClassName = driverClassName; 149 | } 150 | 151 | public String getUrl() { 152 | return url; 153 | } 154 | 155 | public void setUrl(String url) { 156 | this.url = url; 157 | } 158 | 159 | public String getUsername() { 160 | return username; 161 | } 162 | 163 | public void setUsername(String username) { 164 | this.username = username; 165 | } 166 | 167 | public String getPassword() { 168 | return password; 169 | } 170 | 171 | public void setPassword(String password) { 172 | this.password = password; 173 | } 174 | 175 | } 176 | -------------------------------------------------------------------------------- /spring-boot-with-druid/src/main/java/cn/kiiwii/framework/service/ITestService.java: -------------------------------------------------------------------------------- 1 | package cn.kiiwii.framework.service; 2 | 3 | /** 4 | * Created by zhong on 2016/9/5. 5 | */ 6 | public interface ITestService { 7 | 8 | void test(); 9 | 10 | void testTransaction() throws Exception; 11 | } 12 | -------------------------------------------------------------------------------- /spring-boot-with-druid/src/main/java/cn/kiiwii/framework/service/impl/TestServiceImpl.java: -------------------------------------------------------------------------------- 1 | package cn.kiiwii.framework.service.impl; 2 | 3 | import cn.kiiwii.framework.dao.ITestDAO; 4 | import cn.kiiwii.framework.service.ITestService; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.stereotype.Service; 7 | import org.springframework.transaction.annotation.Propagation; 8 | import org.springframework.transaction.annotation.Transactional; 9 | 10 | /** 11 | * Created by zhong on 2016/9/5. 12 | */ 13 | @Service("testService") 14 | public class TestServiceImpl implements ITestService { 15 | 16 | @Autowired 17 | ITestDAO testDAO; 18 | 19 | @Override 20 | public void test() { 21 | this.testDAO.test(); 22 | } 23 | 24 | @Transactional 25 | @Override 26 | public void testTransaction() throws Exception{ 27 | this.testDAO.save(); 28 | int i = 9/0; 29 | this.testDAO.save(); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /spring-boot-with-druid/src/main/resources/application.properties: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhonglinlin1305/spring-boot-sample/efd45c9948a0e4e8379698dbb421852d291f4c45/spring-boot-with-druid/src/main/resources/application.properties -------------------------------------------------------------------------------- /spring-boot-with-druid/src/main/resources/log4j.properties: -------------------------------------------------------------------------------- 1 | log4j.rootLogger=INFO,CONSOLE,ROLLING_FILE 2 | 3 | ################## 4 | #Console Appender 5 | ################## 6 | log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender 7 | log4j.appender.Threshold=INFO 8 | log4j.appender.CONSOLE.Target=System.out 9 | log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout 10 | log4j.appender.CONSOLE.layout.ConversionPattern= [%p] %d %c - %m%n 11 | 12 | ######################## 13 | # Rolling File 14 | ######################## 15 | log4j.appender.ROLLING_FILE=org.apache.log4j.DailyRollingFileAppender 16 | log4j.appender.ROLLING_FILE.Threshold=INFO 17 | log4j.appender.ROLLING_FILE.File=../logs/schedule/consol.log 18 | log4j.appender.ROLLING_FILE.Append=true 19 | log4j.appender.ROLLING_FILE.layout=org.apache.log4j.PatternLayout 20 | log4j.appender.ROLLING_FILE.layout.ConversionPattern=%d{yyyy-M-d HH:mm:ss}%x[%5p](%F:%L) %m%n -------------------------------------------------------------------------------- /spring-boot-with-druid/src/main/script/test.sql: -------------------------------------------------------------------------------- 1 | SELECT * FROM spring.test;CREATE TABLE `test` ( 2 | `id` int(11) NOT NULL AUTO_INCREMENT, 3 | `test_name` varchar(45) DEFAULT NULL, 4 | `test_num` int(11) DEFAULT '0', 5 | `test_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP, 6 | PRIMARY KEY (`id`) 7 | ) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8; -------------------------------------------------------------------------------- /spring-boot-with-dubbo/dobbo-consumer/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | spring-boot-with-dubbo 7 | cn.kiiwii.framework 8 | 1.0-SNAPSHOT 9 | 10 | 4.0.0 11 | 12 | 13 | dobbo-consumer 14 | 15 | 16 | 17 | junit 18 | junit 19 | 4.12 20 | test 21 | 22 | 23 | org.springframework.boot 24 | spring-boot-starter-web 25 | 26 | 27 | org.springframework.boot 28 | spring-boot-starter 29 | 30 | 31 | org.springframework.boot 32 | spring-boot-starter-logging 33 | 34 | 35 | 36 | 37 | org.springframework.boot 38 | spring-boot-starter-log4j 39 | 1.3.7.RELEASE 40 | 41 | 42 | org.springframework.boot 43 | spring-boot-configuration-processor 44 | true 45 | 46 | 47 | com.alibaba 48 | druid 49 | 1.0.25 50 | 51 | 52 | org.springframework 53 | spring-context 54 | 4.3.2.RELEASE 55 | 56 | 57 | cn.kiiwii.framework 58 | dobbo-interface 59 | 1.0-SNAPSHOT 60 | 61 | 62 | cn.kiiwii.framework 63 | spring-boot-dubbo-plugin 64 | 1.0.0-RELEASE 65 | 66 | 67 | 68 | 69 | 70 | org.apache.maven.plugins 71 | maven-compiler-plugin 72 | 3.2 73 | 74 | 1.7 75 | 1.7 76 | 77 | 78 | 79 | org.springframework.boot 80 | spring-boot-maven-plugin 81 | 82 | 83 | 84 | repackage 85 | 86 | 87 | 88 | 89 | 90 | 91 | -------------------------------------------------------------------------------- /spring-boot-with-dubbo/dobbo-consumer/src/main/java/cn/kiiwii/framework/Application.java: -------------------------------------------------------------------------------- 1 | package cn.kiiwii.framework; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.EnableAutoConfiguration; 5 | import org.springframework.boot.autoconfigure.SpringBootApplication; 6 | import org.springframework.context.annotation.ComponentScan; 7 | import org.springframework.context.annotation.Configuration; 8 | 9 | /** 10 | * Created by zhong on 2016/11/22. 11 | */ 12 | @SpringBootApplication 13 | @EnableAutoConfiguration 14 | @Configuration 15 | @ComponentScan(basePackages = {"cn.kiiwii.framework","cn.kiiwii.framework.dubbo"}) 16 | public class Application { 17 | public static void main(String[] args) { 18 | SpringApplication.run(Application.class, args); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /spring-boot-with-dubbo/dobbo-consumer/src/main/java/cn/kiiwii/framework/controller/UserController.java: -------------------------------------------------------------------------------- 1 | package cn.kiiwii.framework.controller; 2 | 3 | import cn.kiiwii.framework.dubbo.api.IPerson; 4 | import com.alibaba.dubbo.config.annotation.Reference; 5 | import org.springframework.web.bind.annotation.PathVariable; 6 | import org.springframework.web.bind.annotation.RequestMapping; 7 | import org.springframework.web.bind.annotation.RestController; 8 | 9 | /** 10 | * Created by zhong on 2016/11/22. 11 | */ 12 | @RestController 13 | @RequestMapping("user") 14 | public class UserController { 15 | @Reference(version = "1.0.0",check = false) 16 | IPerson person; 17 | 18 | @RequestMapping("/{id}") 19 | public String view(@PathVariable("id") int id) { 20 | String result = person.getNickName(id); 21 | return result; 22 | } 23 | @RequestMapping("/info/{name}") 24 | public String view(@PathVariable("name") String name) { 25 | String result = person.getFullName(name); 26 | return result; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /spring-boot-with-dubbo/dobbo-consumer/src/main/resources/application-dev.properties: -------------------------------------------------------------------------------- 1 | server.port=8081 2 | 3 | dubbo.application.name=application_hello 4 | dubbo.application.logger=slf4j 5 | 6 | dubbo.annotation.package-name=cn.kiiwii.framework 7 | 8 | dubbo.protocol.name=dubbo 9 | dubbo.protocol.port=20880 10 | dubbo.protocol.accessLog=true 11 | 12 | dubbo.provider.timeout=3000 13 | dubbo.provider.retries=1 14 | dubbo.provider.delay=-1 15 | 16 | dubbo.registry.protocol=zookeeper 17 | 18 | dubbo.registry.address=192.168.1.113:2181 19 | dubbo.registry.register=true 20 | dubbo.registry.subscribe=true 21 | -------------------------------------------------------------------------------- /spring-boot-with-dubbo/dobbo-consumer/src/main/resources/application-test.properties: -------------------------------------------------------------------------------- 1 | server.port=8081 2 | 3 | dubbo.application.name=application_hello 4 | dubbo.application.logger=slf4j 5 | 6 | dubbo.annotation.package-name=cn.kiiwii.framework 7 | 8 | dubbo.protocol.name=dubbo 9 | dubbo.protocol.port=20880 10 | dubbo.protocol.accessLog=true 11 | 12 | dubbo.provider.timeout=3000 13 | dubbo.provider.retries=1 14 | dubbo.provider.delay=-1 15 | 16 | dubbo.registry.protocol=zookeeper 17 | 18 | dubbo.registry.address=192.168.1.113:2181 19 | dubbo.registry.register=true 20 | dubbo.registry.subscribe=true 21 | -------------------------------------------------------------------------------- /spring-boot-with-dubbo/dobbo-consumer/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | spring.profiles.active=dev -------------------------------------------------------------------------------- /spring-boot-with-dubbo/dobbo-consumer/src/main/resources/log4j.properties: -------------------------------------------------------------------------------- 1 | log4j.rootLogger=INFO,CONSOLE,ROLLING_FILE 2 | 3 | ################## 4 | #Console Appender 5 | ################## 6 | log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender 7 | log4j.appender.Threshold=INFO 8 | log4j.appender.CONSOLE.Target=System.out 9 | log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout 10 | log4j.appender.CONSOLE.layout.ConversionPattern= [%p] %d %c - %m%n 11 | 12 | ######################## 13 | # Rolling File 14 | ######################## 15 | log4j.appender.ROLLING_FILE=org.apache.log4j.DailyRollingFileAppender 16 | log4j.appender.ROLLING_FILE.Threshold=INFO 17 | log4j.appender.ROLLING_FILE.File=../logs/schedule/consol.log 18 | log4j.appender.ROLLING_FILE.Append=true 19 | log4j.appender.ROLLING_FILE.layout=org.apache.log4j.PatternLayout 20 | log4j.appender.ROLLING_FILE.layout.ConversionPattern=%d{yyyy-M-d HH:mm:ss}%x[%5p](%F:%L) %m%n -------------------------------------------------------------------------------- /spring-boot-with-dubbo/dobbo-interface/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | spring-boot-with-dubbo 7 | cn.kiiwii.framework 8 | 1.0-SNAPSHOT 9 | 10 | 4.0.0 11 | jar 12 | 13 | dobbo-interface 14 | 15 | 16 | -------------------------------------------------------------------------------- /spring-boot-with-dubbo/dobbo-interface/src/main/java/cn/kiiwii/framework/dubbo/api/IPerson.java: -------------------------------------------------------------------------------- 1 | package cn.kiiwii.framework.dubbo.api; 2 | 3 | /** 4 | * Created by zhong on 2016/11/22. 5 | */ 6 | public interface IPerson { 7 | String getFullName(String name); 8 | String getNickName(int id); 9 | } 10 | -------------------------------------------------------------------------------- /spring-boot-with-dubbo/dobbo-provider/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | spring-boot-with-dubbo 7 | cn.kiiwii.framework 8 | 1.0-SNAPSHOT 9 | 10 | jar 11 | 4.0.0 12 | 13 | dobbo-provider 14 | 15 | 16 | junit 17 | junit 18 | 4.12 19 | test 20 | 21 | 22 | org.springframework.boot 23 | spring-boot-starter-web 24 | 25 | 26 | org.springframework.boot 27 | spring-boot-starter 28 | 29 | 30 | org.springframework.boot 31 | spring-boot-starter-logging 32 | 33 | 34 | 35 | 36 | org.springframework.boot 37 | spring-boot-configuration-processor 38 | true 39 | 40 | 41 | org.springframework.boot 42 | spring-boot-starter-jdbc 43 | 44 | 45 | org.springframework.boot 46 | spring-boot-starter-jdbc 47 | 48 | 49 | org.springframework.boot 50 | spring-boot-starter-log4j 51 | 1.3.7.RELEASE 52 | 53 | 54 | mysql 55 | mysql-connector-java 56 | 5.1.38 57 | 58 | 59 | com.alibaba 60 | druid 61 | 1.0.25 62 | 63 | 64 | 65 | org.springframework 66 | spring-context 67 | 4.3.2.RELEASE 68 | 69 | 70 | cn.kiiwii.framework 71 | dobbo-interface 72 | 1.0-SNAPSHOT 73 | 74 | 75 | cn.kiiwii.framework 76 | spring-boot-dubbo-plugin 77 | 1.0.0-RELEASE 78 | 79 | 80 | 81 | 82 | 83 | org.apache.maven.plugins 84 | maven-compiler-plugin 85 | 3.2 86 | 87 | 1.7 88 | 1.7 89 | 90 | 91 | 92 | org.springframework.boot 93 | spring-boot-maven-plugin 94 | 95 | 96 | 97 | repackage 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | -------------------------------------------------------------------------------- /spring-boot-with-dubbo/dobbo-provider/src/main/java/cn/kiiwii/framework/dubbo/provider/Application.java: -------------------------------------------------------------------------------- 1 | package cn.kiiwii.framework.dubbo.provider; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.EnableAutoConfiguration; 5 | import org.springframework.boot.autoconfigure.ImportAutoConfiguration; 6 | import org.springframework.boot.autoconfigure.SpringBootApplication; 7 | import org.springframework.boot.context.properties.EnableConfigurationProperties; 8 | import org.springframework.context.annotation.ComponentScan; 9 | import org.springframework.context.annotation.Configuration; 10 | import org.springframework.context.annotation.Import; 11 | import org.springframework.transaction.annotation.EnableTransactionManagement; 12 | 13 | /** 14 | * Created by zhong on 2016/11/22. 15 | */ 16 | @ComponentScan(basePackages = {"cn.kiiwii.framework.dubbo.provider","cn.kiiwii.framework.dubbo"}) 17 | @EnableConfigurationProperties 18 | @SpringBootApplication 19 | @EnableAutoConfiguration 20 | @Configuration 21 | public class Application { 22 | public static void main(String[] args) { 23 | SpringApplication.run(Application.class, args); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /spring-boot-with-dubbo/dobbo-provider/src/main/java/cn/kiiwii/framework/dubbo/provider/dao/ITestDAO.java: -------------------------------------------------------------------------------- 1 | package cn.kiiwii.framework.dubbo.provider.dao; 2 | 3 | /** 4 | * Created by zhong on 2016/11/22. 5 | */ 6 | public interface ITestDAO { 7 | 8 | public Object test(); 9 | } 10 | -------------------------------------------------------------------------------- /spring-boot-with-dubbo/dobbo-provider/src/main/java/cn/kiiwii/framework/dubbo/provider/dao/impl/TestDAOImpl.java: -------------------------------------------------------------------------------- 1 | package cn.kiiwii.framework.dubbo.provider.dao.impl; 2 | 3 | import cn.kiiwii.framework.dubbo.provider.dao.ITestDAO; 4 | import org.springframework.beans.factory.annotation.Autowired; 5 | import org.springframework.jdbc.core.JdbcTemplate; 6 | import org.springframework.stereotype.Repository; 7 | 8 | /** 9 | * Created by zhong on 2016/11/22. 10 | */ 11 | @Repository(value = "testDAO") 12 | public class TestDAOImpl implements ITestDAO { 13 | 14 | @Autowired 15 | private JdbcTemplate jdbcTemplate; 16 | 17 | @Override 18 | public Object test() { 19 | return jdbcTemplate.queryForList("select * from test"); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /spring-boot-with-dubbo/dobbo-provider/src/main/java/cn/kiiwii/framework/dubbo/provider/druid/DruidConfiguration.java: -------------------------------------------------------------------------------- 1 | package cn.kiiwii.framework.dubbo.provider.druid; 2 | 3 | import com.alibaba.druid.pool.DruidDataSource; 4 | import com.alibaba.druid.support.http.StatViewServlet; 5 | import com.alibaba.druid.support.http.WebStatFilter; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; 8 | import org.springframework.boot.context.properties.EnableConfigurationProperties; 9 | import org.springframework.boot.web.servlet.FilterRegistrationBean; 10 | import org.springframework.boot.web.servlet.ServletRegistrationBean; 11 | import org.springframework.context.annotation.Bean; 12 | import org.springframework.context.annotation.Configuration; 13 | 14 | import javax.sql.DataSource; 15 | import java.sql.SQLException; 16 | 17 | /** 18 | * Created by zhong on 2016/9/5. 19 | */ 20 | @Configuration 21 | @EnableConfigurationProperties({DruidDataSourceProperties.class}) 22 | public class DruidConfiguration { 23 | 24 | @Autowired 25 | private DruidDataSourceProperties properties; 26 | 27 | @Bean 28 | @ConditionalOnMissingBean 29 | public DataSource druidDataSource() { 30 | DruidDataSource druidDataSource = new DruidDataSource(); 31 | druidDataSource.setDriverClassName(properties.getDriverClassName()); 32 | druidDataSource.setUrl(properties.getUrl()); 33 | druidDataSource.setUsername(properties.getUsername()); 34 | druidDataSource.setPassword(properties.getPassword()); 35 | druidDataSource.setInitialSize(properties.getInitialSize()); 36 | druidDataSource.setMinIdle(properties.getMinIdle()); 37 | druidDataSource.setMaxActive(properties.getMaxActive()); 38 | druidDataSource.setMaxWait(properties.getMaxWait()); 39 | druidDataSource.setTimeBetweenEvictionRunsMillis(properties.getTimeBetweenEvictionRunsMillis()); 40 | druidDataSource.setMinEvictableIdleTimeMillis(properties.getMinEvictableIdleTimeMillis()); 41 | druidDataSource.setValidationQuery(properties.getValidationQuery()); 42 | druidDataSource.setTestWhileIdle(properties.isTestWhileIdle()); 43 | druidDataSource.setTestOnBorrow(properties.isTestOnBorrow()); 44 | druidDataSource.setTestOnReturn(properties.isTestOnReturn()); 45 | druidDataSource.setPoolPreparedStatements(properties.isPoolPreparedStatements()); 46 | druidDataSource.setMaxPoolPreparedStatementPerConnectionSize(properties.getMaxPoolPreparedStatementPerConnectionSize()); 47 | druidDataSource.setConnectionProperties(properties.getConnectionProperties()); 48 | try { 49 | druidDataSource.setFilters(properties.getFilters()); 50 | druidDataSource.init(); 51 | } catch (SQLException e) { 52 | e.printStackTrace(); 53 | } 54 | 55 | return druidDataSource; 56 | } 57 | 58 | @Bean 59 | @ConditionalOnMissingBean 60 | public ServletRegistrationBean druidServlet() { 61 | 62 | ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*"); 63 | 64 | //添加初始化参数:initParams 65 | 66 | //白名单: 67 | //servletRegistrationBean.addInitParameter("allow","127.0.0.1"); 68 | //IP黑名单 (存在共同时,deny优先于allow) : 如果满足deny的话提示:Sorry, you are not permitted to view this page. 69 | //servletRegistrationBean.addInitParameter("deny","192.168.1.73"); 70 | //登录查看信息的账号密码. 71 | servletRegistrationBean.addInitParameter("loginUsername", "admin"); 72 | servletRegistrationBean.addInitParameter("loginPassword", "admin"); 73 | //是否能够重置数据. 74 | servletRegistrationBean.addInitParameter("resetEnable", "true"); 75 | return servletRegistrationBean; 76 | 77 | } 78 | 79 | @Bean 80 | @ConditionalOnMissingBean 81 | public FilterRegistrationBean filterRegistrationBean() { 82 | FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(); 83 | filterRegistrationBean.setFilter(new WebStatFilter()); 84 | filterRegistrationBean.addUrlPatterns("/*"); 85 | filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*"); 86 | return filterRegistrationBean; 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /spring-boot-with-dubbo/dobbo-provider/src/main/java/cn/kiiwii/framework/dubbo/provider/druid/DruidDataSourceProperties.java: -------------------------------------------------------------------------------- 1 | package cn.kiiwii.framework.dubbo.provider.druid; 2 | 3 | import org.springframework.boot.context.properties.ConfigurationProperties; 4 | 5 | /** 6 | * Created by zhong on 2017/1/7. 7 | */ 8 | @ConfigurationProperties(prefix = "spring.datasource.druid") 9 | public class DruidDataSourceProperties { 10 | 11 | private String driverClassName; 12 | private String url; 13 | private String username; 14 | private String password; 15 | 16 | private int initialSize; 17 | private int minIdle; 18 | private int maxActive; 19 | private long maxWait; 20 | private long timeBetweenEvictionRunsMillis; 21 | private long minEvictableIdleTimeMillis; 22 | private String validationQuery; 23 | private boolean testWhileIdle; 24 | private boolean testOnBorrow; 25 | private boolean testOnReturn; 26 | private boolean poolPreparedStatements; 27 | private int maxPoolPreparedStatementPerConnectionSize; 28 | private String filters; 29 | private String connectionProperties; 30 | 31 | public int getInitialSize() { 32 | return initialSize; 33 | } 34 | 35 | public void setInitialSize(int initialSize) { 36 | this.initialSize = initialSize; 37 | } 38 | 39 | public int getMinIdle() { 40 | return minIdle; 41 | } 42 | 43 | public void setMinIdle(int minIdle) { 44 | this.minIdle = minIdle; 45 | } 46 | 47 | public int getMaxActive() { 48 | return maxActive; 49 | } 50 | 51 | public void setMaxActive(int maxActive) { 52 | this.maxActive = maxActive; 53 | } 54 | 55 | public long getMaxWait() { 56 | return maxWait; 57 | } 58 | 59 | public void setMaxWait(long maxWait) { 60 | this.maxWait = maxWait; 61 | } 62 | 63 | public long getTimeBetweenEvictionRunsMillis() { 64 | return timeBetweenEvictionRunsMillis; 65 | } 66 | 67 | public void setTimeBetweenEvictionRunsMillis(long timeBetweenEvictionRunsMillis) { 68 | this.timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis; 69 | } 70 | 71 | public long getMinEvictableIdleTimeMillis() { 72 | return minEvictableIdleTimeMillis; 73 | } 74 | 75 | public void setMinEvictableIdleTimeMillis(long minEvictableIdleTimeMillis) { 76 | this.minEvictableIdleTimeMillis = minEvictableIdleTimeMillis; 77 | } 78 | 79 | public String getValidationQuery() { 80 | return validationQuery; 81 | } 82 | 83 | public void setValidationQuery(String validationQuery) { 84 | this.validationQuery = validationQuery; 85 | } 86 | 87 | public boolean isTestWhileIdle() { 88 | return testWhileIdle; 89 | } 90 | 91 | public void setTestWhileIdle(boolean testWhileIdle) { 92 | this.testWhileIdle = testWhileIdle; 93 | } 94 | 95 | public boolean isTestOnBorrow() { 96 | return testOnBorrow; 97 | } 98 | 99 | public void setTestOnBorrow(boolean testOnBorrow) { 100 | this.testOnBorrow = testOnBorrow; 101 | } 102 | 103 | public boolean isTestOnReturn() { 104 | return testOnReturn; 105 | } 106 | 107 | public void setTestOnReturn(boolean testOnReturn) { 108 | this.testOnReturn = testOnReturn; 109 | } 110 | 111 | public boolean isPoolPreparedStatements() { 112 | return poolPreparedStatements; 113 | } 114 | 115 | public void setPoolPreparedStatements(boolean poolPreparedStatements) { 116 | this.poolPreparedStatements = poolPreparedStatements; 117 | } 118 | 119 | public int getMaxPoolPreparedStatementPerConnectionSize() { 120 | return maxPoolPreparedStatementPerConnectionSize; 121 | } 122 | 123 | public void setMaxPoolPreparedStatementPerConnectionSize(int maxPoolPreparedStatementPerConnectionSize) { 124 | this.maxPoolPreparedStatementPerConnectionSize = maxPoolPreparedStatementPerConnectionSize; 125 | } 126 | 127 | public String getFilters() { 128 | return filters; 129 | } 130 | 131 | public void setFilters(String filters) { 132 | this.filters = filters; 133 | } 134 | 135 | public String getConnectionProperties() { 136 | return connectionProperties; 137 | } 138 | 139 | public void setConnectionProperties(String connectionProperties) { 140 | this.connectionProperties = connectionProperties; 141 | } 142 | 143 | public String getDriverClassName() { 144 | return driverClassName; 145 | } 146 | 147 | public void setDriverClassName(String driverClassName) { 148 | this.driverClassName = driverClassName; 149 | } 150 | 151 | public String getUrl() { 152 | return url; 153 | } 154 | 155 | public void setUrl(String url) { 156 | this.url = url; 157 | } 158 | 159 | public String getUsername() { 160 | return username; 161 | } 162 | 163 | public void setUsername(String username) { 164 | this.username = username; 165 | } 166 | 167 | public String getPassword() { 168 | return password; 169 | } 170 | 171 | public void setPassword(String password) { 172 | this.password = password; 173 | } 174 | 175 | } 176 | -------------------------------------------------------------------------------- /spring-boot-with-dubbo/dobbo-provider/src/main/java/cn/kiiwii/framework/dubbo/provider/service/PersonServiceImpl.java: -------------------------------------------------------------------------------- 1 | package cn.kiiwii.framework.dubbo.provider.service; 2 | 3 | import cn.kiiwii.framework.dubbo.api.IPerson; 4 | import cn.kiiwii.framework.dubbo.provider.dao.ITestDAO; 5 | import com.alibaba.dubbo.config.annotation.Service; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.stereotype.Component; 8 | 9 | /** 10 | * Created by zhong on 2016/11/22. 11 | */ 12 | @Component 13 | @Service(version="1.0.0") 14 | public class PersonServiceImpl implements IPerson { 15 | 16 | @Autowired 17 | ITestDAO testDAO; 18 | @Override 19 | public String getFullName(String name) { 20 | 21 | return "getFullName:"+this.testDAO.test().toString(); 22 | } 23 | 24 | @Override 25 | public String getNickName(int id) { 26 | return "getNickName:"+this.testDAO.test().toString(); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /spring-boot-with-dubbo/dobbo-provider/src/main/resources/application.properties: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhonglinlin1305/spring-boot-sample/efd45c9948a0e4e8379698dbb421852d291f4c45/spring-boot-with-dubbo/dobbo-provider/src/main/resources/application.properties -------------------------------------------------------------------------------- /spring-boot-with-dubbo/dobbo-provider/src/main/resources/log4j.properties: -------------------------------------------------------------------------------- 1 | log4j.rootLogger=INFO,CONSOLE,ROLLING_FILE 2 | 3 | ################## 4 | #Console Appender 5 | ################## 6 | log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender 7 | log4j.appender.Threshold=INFO 8 | log4j.appender.CONSOLE.Target=System.out 9 | log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout 10 | log4j.appender.CONSOLE.layout.ConversionPattern= [%p] %d %c - %m%n 11 | 12 | ######################## 13 | # Rolling File 14 | ######################## 15 | log4j.appender.ROLLING_FILE=org.apache.log4j.DailyRollingFileAppender 16 | log4j.appender.ROLLING_FILE.Threshold=INFO 17 | log4j.appender.ROLLING_FILE.File=../logs/schedule/consol.log 18 | log4j.appender.ROLLING_FILE.Append=true 19 | log4j.appender.ROLLING_FILE.layout=org.apache.log4j.PatternLayout 20 | log4j.appender.ROLLING_FILE.layout.ConversionPattern=%d{yyyy-M-d HH:mm:ss}%x[%5p](%F:%L) %m%n -------------------------------------------------------------------------------- /spring-boot-with-dubbo/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | spring-boot-sample 7 | cn.kiiwii.framework 8 | 1.0-SNAPSHOT 9 | 10 | 4.0.0 11 | 12 | spring-boot-with-dubbo 13 | pom 14 | 15 | dobbo-interface 16 | dobbo-provider 17 | dobbo-consumer 18 | 19 | -------------------------------------------------------------------------------- /spring-boot-with-dynamic-datasource/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | spring-boot-sample 7 | cn.kiiwii.framework 8 | 1.0-SNAPSHOT 9 | 10 | 4.0.0 11 | 12 | spring-boot-with-dynamic-datasource 13 | 14 | 15 | junit 16 | junit 17 | 4.12 18 | test 19 | 20 | 21 | org.springframework.boot 22 | spring-boot-starter-web 23 | 24 | 25 | org.springframework.boot 26 | spring-boot-starter 27 | 28 | 29 | org.springframework.boot 30 | spring-boot-starter-logging 31 | 32 | 33 | org.springframework.boot 34 | spring-boot-starter-tomcat 35 | 36 | 37 | 38 | 39 | org.springframework.boot 40 | spring-boot-starter-jetty 41 | 42 | 43 | org.springframework.boot 44 | spring-boot-starter-jdbc 45 | 46 | 47 | org.springframework.boot 48 | spring-boot-starter-log4j 49 | 1.3.7.RELEASE 50 | 51 | 52 | mysql 53 | mysql-connector-java 54 | 5.1.38 55 | 56 | 57 | com.alibaba 58 | druid 59 | 1.0.25 60 | 61 | 62 | org.springframework 63 | spring-context 64 | 4.3.2.RELEASE 65 | 66 | 67 | org.springframework 68 | spring-aspects 69 | 4.3.2.RELEASE 70 | 71 | 72 | 73 | 74 | 75 | 76 | org.apache.maven.plugins 77 | maven-compiler-plugin 78 | 3.2 79 | 80 | 1.7 81 | 1.7 82 | 83 | 84 | 85 | org.springframework.boot 86 | spring-boot-maven-plugin 87 | 88 | 89 | 90 | repackage 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | -------------------------------------------------------------------------------- /spring-boot-with-dynamic-datasource/src/main/java/cn/kiiwii/framework/Application.java: -------------------------------------------------------------------------------- 1 | package cn.kiiwii.framework; 2 | 3 | import cn.kiiwii.framework.druid.DynamicDataSource.DynamicDataSourceRegister; 4 | import cn.kiiwii.framework.druid.DynamicDataSource.MProxyTransactionManagementConfiguration; 5 | import org.slf4j.Logger; 6 | import org.slf4j.LoggerFactory; 7 | import org.springframework.boot.SpringApplication; 8 | import org.springframework.boot.autoconfigure.EnableAutoConfiguration; 9 | import org.springframework.boot.autoconfigure.ImportAutoConfiguration; 10 | import org.springframework.boot.autoconfigure.SpringBootApplication; 11 | import org.springframework.context.annotation.Import; 12 | import org.springframework.web.bind.annotation.RestController; 13 | 14 | /** 15 | * Created by zhong on 2016/11/14. 16 | */ 17 | @RestController 18 | @SpringBootApplication 19 | @EnableAutoConfiguration 20 | @ImportAutoConfiguration 21 | @Import({DynamicDataSourceRegister.class, MProxyTransactionManagementConfiguration.class}) 22 | public class Application { 23 | 24 | static Logger logger = LoggerFactory.getLogger(Application.class); 25 | 26 | public static void main(String[] args) throws Exception { 27 | SpringApplication.run(Application.class, args); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /spring-boot-with-dynamic-datasource/src/main/java/cn/kiiwii/framework/controller/TestController.java: -------------------------------------------------------------------------------- 1 | package cn.kiiwii.framework.controller; 2 | 3 | import cn.kiiwii.framework.service.ITestService; 4 | import org.slf4j.Logger; 5 | import org.slf4j.LoggerFactory; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.stereotype.Controller; 8 | import org.springframework.web.bind.annotation.RequestMapping; 9 | import org.springframework.web.bind.annotation.RestController; 10 | 11 | /** 12 | * Created by zhong on 2016/11/10. 13 | */ 14 | @RestController 15 | @Controller 16 | public class TestController { 17 | @Autowired 18 | private ITestService testService; 19 | private Logger logger = LoggerFactory.getLogger(this.getClass()); 20 | 21 | @RequestMapping("/test") 22 | public String greeting() { 23 | testService.test(); 24 | return "hello"; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /spring-boot-with-dynamic-datasource/src/main/java/cn/kiiwii/framework/dao/ITestDAO.java: -------------------------------------------------------------------------------- 1 | package cn.kiiwii.framework.dao; 2 | 3 | /** 4 | * Created by zhong on 2016/9/5. 5 | */ 6 | public interface ITestDAO { 7 | void testMaster(); 8 | void testSlave1(); 9 | void testSlave2(); 10 | } 11 | -------------------------------------------------------------------------------- /spring-boot-with-dynamic-datasource/src/main/java/cn/kiiwii/framework/dao/impl/TestDAOImpl.java: -------------------------------------------------------------------------------- 1 | package cn.kiiwii.framework.dao.impl; 2 | 3 | import cn.kiiwii.framework.druid.DynamicDataSource.TargetDataSource; 4 | import cn.kiiwii.framework.dao.ITestDAO; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.jdbc.core.JdbcTemplate; 7 | import org.springframework.stereotype.Repository; 8 | 9 | import java.util.List; 10 | import java.util.Map; 11 | 12 | /** 13 | * Created by zhong on 2016/9/5. 14 | */ 15 | @Repository("testDAO") 16 | public class TestDAOImpl implements ITestDAO { 17 | 18 | @Autowired 19 | private JdbcTemplate jdbcTemplate; 20 | 21 | @Override 22 | public void testMaster() { 23 | List> list = this.jdbcTemplate.queryForList("select * from test"); 24 | System.out.println(list); 25 | } 26 | @TargetDataSource(name="slave1") 27 | @Override 28 | public void testSlave1() { 29 | List> list = this.jdbcTemplate.queryForList("select * from test"); 30 | System.out.println(list); 31 | } 32 | 33 | @TargetDataSource(name="slave2") 34 | @Override 35 | public void testSlave2() { 36 | List> list = this.jdbcTemplate.queryForList("select * from test"); 37 | System.out.println(list); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /spring-boot-with-dynamic-datasource/src/main/java/cn/kiiwii/framework/druid/DruidConfiguration.java: -------------------------------------------------------------------------------- 1 | package cn.kiiwii.framework.druid; 2 | 3 | import com.alibaba.druid.support.http.StatViewServlet; 4 | import com.alibaba.druid.support.http.WebStatFilter; 5 | import org.springframework.beans.factory.annotation.Value; 6 | import org.springframework.boot.web.servlet.FilterRegistrationBean; 7 | import org.springframework.boot.web.servlet.ServletRegistrationBean; 8 | import org.springframework.context.annotation.Bean; 9 | import org.springframework.context.annotation.Configuration; 10 | 11 | /** 12 | * Created by zhong on 2016/9/5. 13 | */ 14 | @Configuration 15 | public class DruidConfiguration { 16 | @Bean 17 | public ServletRegistrationBean druidServlet() { 18 | 19 | ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*"); 20 | 21 | //添加初始化参数:initParams 22 | 23 | //白名单: 24 | //servletRegistrationBean.addInitParameter("allow","127.0.0.1"); 25 | //IP黑名单 (存在共同时,deny优先于allow) : 如果满足deny的话提示:Sorry, you are not permitted to view this page. 26 | //servletRegistrationBean.addInitParameter("deny","192.168.1.73"); 27 | //登录查看信息的账号密码. 28 | servletRegistrationBean.addInitParameter("loginUsername", "admin"); 29 | servletRegistrationBean.addInitParameter("loginPassword", "admin"); 30 | //是否能够重置数据. 31 | servletRegistrationBean.addInitParameter("resetEnable", "true"); 32 | return servletRegistrationBean; 33 | 34 | } 35 | 36 | @Bean 37 | public FilterRegistrationBean filterRegistrationBean() { 38 | FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(); 39 | filterRegistrationBean.setFilter(new WebStatFilter()); 40 | filterRegistrationBean.addUrlPatterns("/*"); 41 | filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*"); 42 | return filterRegistrationBean; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /spring-boot-with-dynamic-datasource/src/main/java/cn/kiiwii/framework/druid/DynamicDataSource/DynamicDataSource.java: -------------------------------------------------------------------------------- 1 | package cn.kiiwii.framework.druid.DynamicDataSource; 2 | 3 | import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource; 4 | 5 | /** 6 | * Created by zhong on 2016/11/14. 7 | */ 8 | public class DynamicDataSource extends AbstractRoutingDataSource { 9 | 10 | @Override 11 | protected Object determineCurrentLookupKey() { 12 | return DynamicDataSourceContextHolder.getDataSourceType(); 13 | } 14 | 15 | } -------------------------------------------------------------------------------- /spring-boot-with-dynamic-datasource/src/main/java/cn/kiiwii/framework/druid/DynamicDataSource/DynamicDataSourceAspect.java: -------------------------------------------------------------------------------- 1 | package cn.kiiwii.framework.druid.DynamicDataSource; 2 | 3 | import org.aspectj.lang.JoinPoint; 4 | import org.aspectj.lang.annotation.After; 5 | import org.aspectj.lang.annotation.Aspect; 6 | import org.aspectj.lang.annotation.Before; 7 | import org.slf4j.Logger; 8 | import org.slf4j.LoggerFactory; 9 | import org.springframework.core.annotation.Order; 10 | import org.springframework.stereotype.Component; 11 | 12 | /** 13 | * Created by zhong on 2016/11/14. 14 | */ 15 | @Aspect 16 | @Order(-1)// 保证该AOP在@Transactional之前执行 17 | @Component 18 | public class DynamicDataSourceAspect { 19 | 20 | private static final Logger logger = LoggerFactory.getLogger(DynamicDataSourceAspect.class); 21 | 22 | @Before("@annotation(ds)") 23 | public void changeDataSource(JoinPoint point, TargetDataSource ds) throws Throwable { 24 | String dsId = ds.name(); 25 | if (!DynamicDataSourceContextHolder.containsDataSource(dsId)) { 26 | logger.error("数据源[{}]不存在,使用默认数据源 > {}", ds.name(), point.getSignature()); 27 | } else { 28 | logger.debug("Use DataSource : {} > {}", ds.name(), point.getSignature()); 29 | DynamicDataSourceContextHolder.setDataSourceType(ds.name()); 30 | } 31 | } 32 | 33 | @After("@annotation(ds)") 34 | public void restoreDataSource(JoinPoint point, TargetDataSource ds) { 35 | logger.debug("Revert DataSource : {} > {}", ds.name(), point.getSignature()); 36 | DynamicDataSourceContextHolder.clearDataSourceType(); 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /spring-boot-with-dynamic-datasource/src/main/java/cn/kiiwii/framework/druid/DynamicDataSource/DynamicDataSourceContextHolder.java: -------------------------------------------------------------------------------- 1 | package cn.kiiwii.framework.druid.DynamicDataSource; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | /** 7 | * Created by zhong on 2016/11/14. 8 | */ 9 | public class DynamicDataSourceContextHolder { 10 | private static final ThreadLocal contextHolder = new ThreadLocal(); 11 | public static List dataSourceIds = new ArrayList<>(); 12 | 13 | public static void setDataSourceType(String dataSourceType) { 14 | contextHolder.set(dataSourceType); 15 | } 16 | 17 | public static String getDataSourceType() { 18 | return contextHolder.get(); 19 | } 20 | 21 | public static void clearDataSourceType() { 22 | contextHolder.remove(); 23 | } 24 | 25 | /** 26 | * 判断指定DataSrouce当前是否存在 27 | * 28 | * @param dataSourceId 29 | * @return 30 | * @author SHANHY 31 | * @create 2016年1月24日 32 | */ 33 | public static boolean containsDataSource(String dataSourceId){ 34 | return dataSourceIds.contains(dataSourceId); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /spring-boot-with-dynamic-datasource/src/main/java/cn/kiiwii/framework/druid/DynamicDataSource/MProxyTransactionManagementConfiguration.java: -------------------------------------------------------------------------------- 1 | package cn.kiiwii.framework.druid.DynamicDataSource; 2 | 3 | /** 4 | * Created by zhong on 2016/11/14. 5 | */ 6 | public class MProxyTransactionManagementConfiguration { 7 | } 8 | -------------------------------------------------------------------------------- /spring-boot-with-dynamic-datasource/src/main/java/cn/kiiwii/framework/druid/DynamicDataSource/MTransactionInterceptor.java: -------------------------------------------------------------------------------- 1 | package cn.kiiwii.framework.druid.DynamicDataSource; 2 | 3 | /** 4 | * Created by zhong on 2016/11/14. 5 | */ 6 | public class MTransactionInterceptor { 7 | } 8 | -------------------------------------------------------------------------------- /spring-boot-with-dynamic-datasource/src/main/java/cn/kiiwii/framework/druid/DynamicDataSource/TargetDataSource.java: -------------------------------------------------------------------------------- 1 | package cn.kiiwii.framework.druid.DynamicDataSource; 2 | 3 | import java.lang.annotation.*; 4 | 5 | /** 6 | * Created by zhong on 2016/11/14. 7 | */ 8 | @Target({ ElementType.METHOD, ElementType.TYPE }) 9 | @Retention(RetentionPolicy.RUNTIME) 10 | @Documented 11 | public @interface TargetDataSource { 12 | String name(); 13 | } -------------------------------------------------------------------------------- /spring-boot-with-dynamic-datasource/src/main/java/cn/kiiwii/framework/service/ITestService.java: -------------------------------------------------------------------------------- 1 | package cn.kiiwii.framework.service; 2 | 3 | /** 4 | * Created by zhong on 2016/9/5. 5 | */ 6 | public interface ITestService { 7 | 8 | void test(); 9 | } 10 | -------------------------------------------------------------------------------- /spring-boot-with-dynamic-datasource/src/main/java/cn/kiiwii/framework/service/impl/TestServiceImpl.java: -------------------------------------------------------------------------------- 1 | package cn.kiiwii.framework.service.impl; 2 | 3 | import cn.kiiwii.framework.dao.ITestDAO; 4 | import cn.kiiwii.framework.service.ITestService; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.stereotype.Service; 7 | 8 | /** 9 | * Created by zhong on 2016/9/5. 10 | */ 11 | @Service("testService") 12 | public class TestServiceImpl implements ITestService { 13 | 14 | @Autowired 15 | ITestDAO testDAO; 16 | 17 | @Override 18 | public void test() { 19 | this.testDAO.testMaster(); 20 | this.testDAO.testSlave1(); 21 | this.testDAO.testSlave2(); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /spring-boot-with-dynamic-datasource/src/main/resources/application.properties: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhonglinlin1305/spring-boot-sample/efd45c9948a0e4e8379698dbb421852d291f4c45/spring-boot-with-dynamic-datasource/src/main/resources/application.properties -------------------------------------------------------------------------------- /spring-boot-with-dynamic-datasource/src/main/resources/log4j.properties: -------------------------------------------------------------------------------- 1 | log4j.rootLogger=INFO,CONSOLE,ROLLING_FILE 2 | 3 | ################## 4 | #Console Appender 5 | ################## 6 | log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender 7 | log4j.appender.Threshold=INFO 8 | log4j.appender.CONSOLE.Target=System.out 9 | log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout 10 | log4j.appender.CONSOLE.layout.ConversionPattern= [%p] %d %c - %m%n 11 | 12 | ######################## 13 | # Rolling File 14 | ######################## 15 | log4j.appender.ROLLING_FILE=org.apache.log4j.DailyRollingFileAppender 16 | log4j.appender.ROLLING_FILE.Threshold=INFO 17 | log4j.appender.ROLLING_FILE.File=../logs/schedule/consol.log 18 | log4j.appender.ROLLING_FILE.Append=true 19 | log4j.appender.ROLLING_FILE.layout=org.apache.log4j.PatternLayout 20 | log4j.appender.ROLLING_FILE.layout.ConversionPattern=%d{yyyy-M-d HH:mm:ss}%x[%5p](%F:%L) %m%n 21 | 22 | log4j.logger.cn.kiiwii.framework.druid.DynamicDataSource =ALL -------------------------------------------------------------------------------- /spring-boot-with-dynamic-datasource/src/main/script/test.sql: -------------------------------------------------------------------------------- 1 | SELECT * FROM spring.test;CREATE TABLE `test` ( 2 | `id` int(11) NOT NULL AUTO_INCREMENT, 3 | `test_name` varchar(45) DEFAULT NULL, 4 | `test_num` int(11) DEFAULT '0', 5 | `test_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP, 6 | PRIMARY KEY (`id`) 7 | ) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8; -------------------------------------------------------------------------------- /spring-boot-with-freemarker/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | spring-boot-sample 7 | cn.kiiwii.framework 8 | 1.0-SNAPSHOT 9 | 10 | 4.0.0 11 | 12 | spring-boot-with-freemarker 13 | 14 | 15 | junit 16 | junit 17 | 4.12 18 | test 19 | 20 | 21 | org.springframework.boot 22 | spring-boot-starter-web 23 | 24 | 25 | 26 | org.springframework.boot 27 | spring-boot-starter-freemarker 28 | 29 | 30 | 31 | org.springframework.boot 32 | spring-boot-starter 33 | 34 | 35 | org.springframework.boot 36 | spring-boot-starter-logging 37 | 38 | 39 | 40 | 41 | org.springframework.boot 42 | spring-boot-configuration-processor 43 | true 44 | 45 | 46 | org.springframework.boot 47 | spring-boot-starter-log4j 48 | 1.3.7.RELEASE 49 | 50 | 51 | org.springframework.boot 52 | spring-boot-starter-aop 53 | 54 | 55 | org.springframework 56 | spring-context 57 | 4.3.2.RELEASE 58 | 59 | 60 | org.springframework 61 | spring-orm 62 | 4.3.2.RELEASE 63 | 64 | 65 | 66 | 67 | 68 | 69 | org.apache.maven.plugins 70 | maven-compiler-plugin 71 | 3.2 72 | 73 | 1.8 74 | 1.8 75 | 76 | 77 | 78 | org.springframework.boot 79 | spring-boot-maven-plugin 80 | 81 | 82 | 83 | repackage 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | -------------------------------------------------------------------------------- /spring-boot-with-freemarker/src/main/java/cn/kiiwii/framework/freemarker/Application.java: -------------------------------------------------------------------------------- 1 | package cn.kiiwii.framework.freemarker; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | import org.springframework.boot.SpringApplication; 6 | import org.springframework.boot.autoconfigure.EnableAutoConfiguration; 7 | import org.springframework.boot.autoconfigure.ImportAutoConfiguration; 8 | import org.springframework.boot.autoconfigure.SpringBootApplication; 9 | import org.springframework.boot.builder.SpringApplicationBuilder; 10 | import org.springframework.boot.context.properties.EnableConfigurationProperties; 11 | import org.springframework.boot.web.support.SpringBootServletInitializer; 12 | import org.springframework.context.annotation.Configuration; 13 | 14 | /** 15 | * Created by zhong on 2017/3/28. 16 | */ 17 | @SpringBootApplication 18 | public class Application extends SpringBootServletInitializer { 19 | 20 | static Logger logger = LoggerFactory.getLogger(Application.class); 21 | 22 | public static void main(String[] args) throws Exception { 23 | SpringApplication.run(Application.class, args); 24 | } 25 | @Override 26 | protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { 27 | return application.sources(Application.class); 28 | } 29 | } -------------------------------------------------------------------------------- /spring-boot-with-freemarker/src/main/java/cn/kiiwii/framework/freemarker/controller/ApiController.java: -------------------------------------------------------------------------------- 1 | package cn.kiiwii.framework.freemarker.controller; 2 | 3 | import org.springframework.stereotype.Controller; 4 | import org.springframework.web.bind.annotation.PathVariable; 5 | import org.springframework.web.bind.annotation.RequestMapping; 6 | import org.springframework.web.bind.annotation.ResponseBody; 7 | import org.springframework.web.bind.annotation.RestController; 8 | import org.springframework.web.multipart.MultipartFile; 9 | import org.springframework.web.multipart.MultipartHttpServletRequest; 10 | 11 | import javax.servlet.http.HttpServletRequest; 12 | import java.util.Map; 13 | 14 | /** 15 | * Created by zhong on 2016/11/10. 16 | */ 17 | @RestController 18 | @Controller 19 | @RequestMapping("/api") 20 | public class ApiController { 21 | 22 | @RequestMapping("/doAction") 23 | @ResponseBody 24 | public Object newsList(HttpServletRequest request) { 25 | try { 26 | Map fileMap = null; 27 | MultipartHttpServletRequest multipartRequest = null; 28 | if (request instanceof MultipartHttpServletRequest) { 29 | multipartRequest = (MultipartHttpServletRequest) request; 30 | } 31 | if (multipartRequest != null) 32 | fileMap = multipartRequest.getFileMap(); 33 | 34 | return ""; 35 | } catch (Exception e) { 36 | return ""; 37 | } 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /spring-boot-with-freemarker/src/main/java/cn/kiiwii/framework/freemarker/controller/WebController.java: -------------------------------------------------------------------------------- 1 | package cn.kiiwii.framework.freemarker.controller; 2 | 3 | import org.springframework.stereotype.Controller; 4 | import org.springframework.ui.ModelMap; 5 | import org.springframework.web.bind.annotation.RequestMapping; 6 | import org.springframework.web.bind.annotation.ResponseBody; 7 | 8 | /** 9 | * Created by zhong on 2016/11/10. 10 | */ 11 | @Controller 12 | public class WebController { 13 | 14 | @RequestMapping("/index") 15 | public String index(ModelMap modelMap) { 16 | return "index"; 17 | } 18 | 19 | } 20 | -------------------------------------------------------------------------------- /spring-boot-with-freemarker/src/main/java/cn/kiiwii/framework/freemarker/model/User.java: -------------------------------------------------------------------------------- 1 | package cn.kiiwii.framework.freemarker.model; 2 | 3 | /** 4 | * Created by zhong on 2017/3/28. 5 | */ 6 | public class User { 7 | private int id; 8 | private String name; 9 | private String account; 10 | private String password; 11 | 12 | public User() { 13 | } 14 | 15 | public User(int id, String name, String account, String password) { 16 | this.id = id; 17 | this.name = name; 18 | this.account = account; 19 | this.password = password; 20 | } 21 | 22 | public int getId() { 23 | return id; 24 | } 25 | 26 | public void setId(int id) { 27 | this.id = id; 28 | } 29 | 30 | public String getName() { 31 | return name; 32 | } 33 | 34 | public void setName(String name) { 35 | this.name = name; 36 | } 37 | 38 | public String getAccount() { 39 | return account; 40 | } 41 | 42 | public void setAccount(String account) { 43 | this.account = account; 44 | } 45 | 46 | public String getPassword() { 47 | return password; 48 | } 49 | 50 | public void setPassword(String password) { 51 | this.password = password; 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /spring-boot-with-freemarker/src/main/java/cn/kiiwii/framework/freemarker/service/IApiService.java: -------------------------------------------------------------------------------- 1 | package cn.kiiwii.framework.freemarker.service; 2 | 3 | /** 4 | * Created by zhong on 2017/3/28. 5 | */ 6 | public interface IApiService { 7 | } 8 | -------------------------------------------------------------------------------- /spring-boot-with-freemarker/src/main/java/cn/kiiwii/framework/freemarker/service/impl/ApiServiceImpl.java: -------------------------------------------------------------------------------- 1 | package cn.kiiwii.framework.freemarker.service.impl; 2 | 3 | import cn.kiiwii.framework.freemarker.service.IApiService; 4 | 5 | /** 6 | * Created by zhong on 2017/3/28. 7 | */ 8 | public class ApiServiceImpl implements IApiService{ 9 | 10 | 11 | } 12 | -------------------------------------------------------------------------------- /spring-boot-with-freemarker/src/main/resources/application-dev.properties: -------------------------------------------------------------------------------- 1 | server.port=8080 2 | spring.aop.auto=true 3 | spring.aop.proxy-target-class=true 4 | 5 | spring.http.multipart.max-file-size=10MB 6 | 7 | # FREEMARKER (FreeMarkerAutoConfiguration) 8 | spring.freemarker.allow-request-override=false 9 | spring.freemarker.allow-session-override=false 10 | spring.freemarker.cache=true 11 | spring.freemarker.charset=UTF-8 12 | spring.freemarker.check-template-location=true 13 | spring.freemarker.content-type=text/html 14 | spring.freemarker.enabled=true 15 | spring.freemarker.expose-request-attributes=false 16 | spring.freemarker.expose-session-attributes=false 17 | spring.freemarker.expose-spring-macro-helpers=true 18 | spring.freemarker.prefer-file-system-access=true 19 | spring.freemarker.suffix=.html 20 | spring.freemarker.template-loader-path=classpath:/templates/ 21 | spring.freemarker.settings.template_update_delay=0 22 | spring.freemarker.settings.default_encoding=UTF-8 23 | spring.freemarker.settings.url_escaping_charset=UTF-8 24 | spring.freemarker.settings.classic_compatible=true 25 | spring.freemarker.settings.number_format=### 26 | 27 | server.tomcat.uri-encoding=UTF-8 -------------------------------------------------------------------------------- /spring-boot-with-freemarker/src/main/resources/application-prod.properties: -------------------------------------------------------------------------------- 1 | server.port=7070 2 | spring.aop.auto=true 3 | spring.aop.proxy-target-class=true 4 | 5 | spring.http.multipart.max-file-size=10MB 6 | 7 | # FREEMARKER (FreeMarkerAutoConfiguration) 8 | spring.freemarker.allow-request-override=false 9 | spring.freemarker.allow-session-override=false 10 | spring.freemarker.cache=true 11 | spring.freemarker.charset=UTF-8 12 | spring.freemarker.check-template-location=true 13 | spring.freemarker.content-type=text/html 14 | spring.freemarker.enabled=true 15 | spring.freemarker.expose-request-attributes=false 16 | spring.freemarker.expose-session-attributes=false 17 | spring.freemarker.expose-spring-macro-helpers=true 18 | spring.freemarker.prefer-file-system-access=true 19 | spring.freemarker.suffix=.html 20 | spring.freemarker.template-loader-path=classpath:/templates/ 21 | spring.freemarker.settings.template_update_delay=0 22 | spring.freemarker.settings.default_encoding=UTF-8 23 | spring.freemarker.settings.url_escaping_charset=UTF-8 24 | spring.freemarker.settings.classic_compatible=true 25 | spring.freemarker.settings.number_format=### 26 | 27 | server.tomcat.uri-encoding=UTF-8 28 | -------------------------------------------------------------------------------- /spring-boot-with-freemarker/src/main/resources/application-test.properties: -------------------------------------------------------------------------------- 1 | server.port=8080 2 | spring.aop.auto=true 3 | spring.aop.proxy-target-class=true 4 | spring.http.multipart.max-file-size=10MB 5 | 6 | # FREEMARKER (FreeMarkerAutoConfiguration) 7 | spring.freemarker.allow-request-override=false 8 | spring.freemarker.allow-session-override=false 9 | spring.freemarker.cache=true 10 | spring.freemarker.charset=UTF-8 11 | spring.freemarker.check-template-location=true 12 | spring.freemarker.content-type=text/html 13 | spring.freemarker.enabled=true 14 | spring.freemarker.expose-request-attributes=false 15 | spring.freemarker.expose-session-attributes=false 16 | spring.freemarker.expose-spring-macro-helpers=true 17 | spring.freemarker.prefer-file-system-access=true 18 | spring.freemarker.suffix=.html 19 | spring.freemarker.template-loader-path=classpath:/templates/ 20 | spring.freemarker.settings.template_update_delay=0 21 | spring.freemarker.settings.default_encoding=UTF-8 22 | spring.freemarker.settings.url_escaping_charset=UTF-8 23 | spring.freemarker.settings.classic_compatible=true 24 | spring.freemarker.settings.number_format=### 25 | 26 | server.tomcat.uri-encoding=UTF-8 27 | -------------------------------------------------------------------------------- /spring-boot-with-freemarker/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | spring.profiles.active=test -------------------------------------------------------------------------------- /spring-boot-with-freemarker/src/main/resources/log4j.properties: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhonglinlin1305/spring-boot-sample/efd45c9948a0e4e8379698dbb421852d291f4c45/spring-boot-with-freemarker/src/main/resources/log4j.properties -------------------------------------------------------------------------------- /spring-boot-with-freemarker/src/main/resources/static/bootstrap/fonts/bootstrap/glyphicons-halflings-regular.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhonglinlin1305/spring-boot-sample/efd45c9948a0e4e8379698dbb421852d291f4c45/spring-boot-with-freemarker/src/main/resources/static/bootstrap/fonts/bootstrap/glyphicons-halflings-regular.eot -------------------------------------------------------------------------------- /spring-boot-with-freemarker/src/main/resources/static/bootstrap/fonts/bootstrap/glyphicons-halflings-regular.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhonglinlin1305/spring-boot-sample/efd45c9948a0e4e8379698dbb421852d291f4c45/spring-boot-with-freemarker/src/main/resources/static/bootstrap/fonts/bootstrap/glyphicons-halflings-regular.ttf -------------------------------------------------------------------------------- /spring-boot-with-freemarker/src/main/resources/static/bootstrap/fonts/bootstrap/glyphicons-halflings-regular.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhonglinlin1305/spring-boot-sample/efd45c9948a0e4e8379698dbb421852d291f4c45/spring-boot-with-freemarker/src/main/resources/static/bootstrap/fonts/bootstrap/glyphicons-halflings-regular.woff -------------------------------------------------------------------------------- /spring-boot-with-freemarker/src/main/resources/static/bootstrap/fonts/bootstrap/glyphicons-halflings-regular.woff2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhonglinlin1305/spring-boot-sample/efd45c9948a0e4e8379698dbb421852d291f4c45/spring-boot-with-freemarker/src/main/resources/static/bootstrap/fonts/bootstrap/glyphicons-halflings-regular.woff2 -------------------------------------------------------------------------------- /spring-boot-with-freemarker/src/main/resources/templates/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 9 | 10 | 11 | 首页 12 | 13 | 14 | 15 |

这是freemarker

16 |
17 |
18 |
19 |
20 |
21 | 22 |
23 |
24 | 25 |
26 | 27 |
28 |
29 |
30 |
31 | 32 |
33 |
34 | 35 | 36 | -------------------------------------------------------------------------------- /spring-boot-with-hibernate/README.md: -------------------------------------------------------------------------------- 1 | #spring-boot 集成hibernate 2 | 3 | 该集成是spring-boot集成hibernate,使用alibaba的druid连接池,dao继承HibernateDaoSupport 4 | 5 | 6 | -------------------------------------------------------------------------------- /spring-boot-with-hibernate/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | spring-boot-sample 7 | cn.kiiwii.framework 8 | 1.0-SNAPSHOT 9 | 10 | 4.0.0 11 | 12 | 13 | 4.3.5.Final 14 | 15 | spring-boot-with-hibernate 16 | 17 | 18 | junit 19 | junit 20 | 4.12 21 | test 22 | 23 | 24 | org.springframework.boot 25 | spring-boot-starter-web 26 | 27 | 28 | org.springframework.boot 29 | spring-boot-starter 30 | 31 | 32 | org.springframework.boot 33 | spring-boot-starter-logging 34 | 35 | 36 | 37 | 38 | org.springframework.boot 39 | spring-boot-configuration-processor 40 | true 41 | 42 | 43 | org.springframework.boot 44 | spring-boot-starter-jdbc 45 | 46 | 47 | org.springframework.boot 48 | spring-boot-starter-log4j 49 | 1.3.7.RELEASE 50 | 51 | 52 | org.springframework.boot 53 | spring-boot-starter-aop 54 | 55 | 56 | mysql 57 | mysql-connector-java 58 | 5.1.38 59 | 60 | 61 | com.alibaba 62 | druid 63 | 1.0.25 64 | 65 | 66 | org.springframework 67 | spring-context 68 | 4.3.2.RELEASE 69 | 70 | 71 | org.springframework 72 | spring-orm 73 | 4.3.2.RELEASE 74 | 75 | 76 | org.eclipse.jetty.websocket 77 | websocket-common 78 | 9.3.11.v20160721 79 | 80 | 81 | 82 | 83 | org.hibernate 84 | hibernate-core 85 | ${hibernate.version} 86 | 87 | 88 | org.hibernate 89 | hibernate-entitymanager 90 | ${hibernate.version} 91 | 92 | 93 | 94 | 95 | 96 | 97 | org.apache.maven.plugins 98 | maven-compiler-plugin 99 | 3.2 100 | 101 | 1.7 102 | 1.7 103 | 104 | 105 | 106 | org.springframework.boot 107 | spring-boot-maven-plugin 108 | 109 | 110 | 111 | repackage 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | -------------------------------------------------------------------------------- /spring-boot-with-hibernate/src/main/java/cn/kiiwii/framework/hibernate/Application.java: -------------------------------------------------------------------------------- 1 | package cn.kiiwii.framework.hibernate; 2 | 3 | import cn.kiiwii.framework.hibernate.conf.ApplicationConfiguration; 4 | import org.slf4j.Logger; 5 | import org.slf4j.LoggerFactory; 6 | import org.springframework.boot.SpringApplication; 7 | import org.springframework.boot.autoconfigure.EnableAutoConfiguration; 8 | import org.springframework.boot.autoconfigure.ImportAutoConfiguration; 9 | import org.springframework.boot.autoconfigure.SpringBootApplication; 10 | import org.springframework.boot.builder.SpringApplicationBuilder; 11 | import org.springframework.boot.web.support.SpringBootServletInitializer; 12 | import org.springframework.context.annotation.Bean; 13 | import org.springframework.context.annotation.Configuration; 14 | import org.springframework.context.annotation.Import; 15 | import org.springframework.jdbc.datasource.DataSourceTransactionManager; 16 | import org.springframework.transaction.PlatformTransactionManager; 17 | import org.springframework.transaction.annotation.EnableTransactionManagement; 18 | import org.springframework.web.bind.annotation.RestController; 19 | 20 | import javax.sql.DataSource; 21 | 22 | /** 23 | * Created by zhong on 2016/11/10. 24 | */ 25 | @SpringBootApplication 26 | @EnableAutoConfiguration 27 | @ImportAutoConfiguration 28 | @Import({ApplicationConfiguration.class}) 29 | @EnableTransactionManagement 30 | public class Application extends SpringBootServletInitializer { 31 | 32 | static Logger logger = LoggerFactory.getLogger(Application.class); 33 | 34 | @Override 35 | protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { 36 | return application.sources(Application.class); 37 | } 38 | 39 | public static void main(String[] args) throws Exception { 40 | SpringApplication.run(Application.class, args); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /spring-boot-with-hibernate/src/main/java/cn/kiiwii/framework/hibernate/aop/ServiceAop.java: -------------------------------------------------------------------------------- 1 | package cn.kiiwii.framework.hibernate.aop; 2 | 3 | import org.aspectj.lang.JoinPoint; 4 | import org.aspectj.lang.ProceedingJoinPoint; 5 | import org.aspectj.lang.annotation.*; 6 | import org.slf4j.Logger; 7 | import org.slf4j.LoggerFactory; 8 | import org.springframework.stereotype.Component; 9 | import org.springframework.web.context.request.RequestContextHolder; 10 | import org.springframework.web.context.request.ServletRequestAttributes; 11 | 12 | import javax.servlet.http.HttpServletRequest; 13 | 14 | /** 15 | * Created by zhong on 2016/11/24. 16 | */ 17 | @Aspect 18 | @Component 19 | public class ServiceAop { 20 | private static Logger logger = LoggerFactory.getLogger(ServiceAop.class); 21 | 22 | private ThreadLocal tlocal = new ThreadLocal(); 23 | 24 | @Pointcut("execution(public * cn.kiiwii.framework.hibernate.service.impl.*.*(..))") 25 | public void webRequestLog() { 26 | } 27 | 28 | @Before("webRequestLog()") 29 | public void doBefore(JoinPoint joinPoint) { 30 | 31 | long beginTime = System.currentTimeMillis(); 32 | 33 | tlocal.set(beginTime); 34 | } 35 | 36 | @AfterReturning(returning = "result", pointcut = "webRequestLog()") 37 | public void doAfterReturning(Object result) { 38 | logger.info("消耗时间: " + (System.currentTimeMillis() - tlocal.get())); 39 | } 40 | 41 | @Around("webRequestLog()") 42 | public Object around(ProceedingJoinPoint pjp) throws Throwable { 43 | System.out.println("方法环绕start....."); 44 | Object o = null; 45 | System.out.println("before---------------------"); 46 | o = pjp.proceed(); 47 | System.out.println("after---------------------"); 48 | return o; 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /spring-boot-with-hibernate/src/main/java/cn/kiiwii/framework/hibernate/conf/ApplicationConfiguration.java: -------------------------------------------------------------------------------- 1 | package cn.kiiwii.framework.hibernate.conf; 2 | 3 | import com.alibaba.druid.pool.DruidDataSource; 4 | import org.hibernate.SessionFactory; 5 | import org.slf4j.Logger; 6 | import org.slf4j.LoggerFactory; 7 | import org.springframework.beans.factory.FactoryBean; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.boot.autoconfigure.ImportAutoConfiguration; 10 | import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; 11 | import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass; 12 | import org.springframework.boot.bind.RelaxedPropertyResolver; 13 | import org.springframework.boot.context.properties.EnableConfigurationProperties; 14 | import org.springframework.context.EnvironmentAware; 15 | import org.springframework.context.annotation.Bean; 16 | import org.springframework.context.annotation.Configuration; 17 | import org.springframework.core.env.Environment; 18 | import org.springframework.jdbc.datasource.DataSourceTransactionManager; 19 | import org.springframework.orm.hibernate4.HibernateTransactionManager; 20 | import org.springframework.orm.hibernate4.LocalSessionFactoryBean; 21 | 22 | import javax.sql.DataSource; 23 | import java.sql.SQLException; 24 | import java.util.Properties; 25 | 26 | /** 27 | * Created by zhong on 2017/1/5. 28 | */ 29 | 30 | @Configuration 31 | @EnableConfigurationProperties({DruidDataSourceProperties.class,HibernatePropertes.class}) 32 | @ConditionalOnMissingClass 33 | public class ApplicationConfiguration { 34 | 35 | Logger logger = LoggerFactory.getLogger(this.getClass()); 36 | @Autowired 37 | private DruidDataSourceProperties druidDataSourceProperties; 38 | @Autowired 39 | private HibernatePropertes hibernatePropertes; 40 | 41 | @Bean(name = "dataSource") 42 | @ConditionalOnMissingBean 43 | public DataSource setDataSource(){ 44 | DruidDataSource dataSource = new DruidDataSource(); 45 | dataSource.setDriverClassName(druidDataSourceProperties.getDriverClassName()); 46 | dataSource.setUrl(druidDataSourceProperties.getUrl()); 47 | dataSource.setUsername(druidDataSourceProperties.getUsername()); 48 | dataSource.setPassword(druidDataSourceProperties.getPassword()); 49 | try { 50 | dataSource.init(); 51 | } catch (SQLException e) { 52 | e.printStackTrace(); 53 | } 54 | return dataSource; 55 | } 56 | 57 | 58 | @Bean(name = "sessionFactory") 59 | @ConditionalOnMissingBean 60 | public LocalSessionFactoryBean setSessionFactory(DataSource dataSource){ 61 | LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean(); 62 | Properties properties = new Properties(); 63 | properties.setProperty("hibernate.show_sql",String.valueOf(hibernatePropertes.isShowSql())); 64 | properties.setProperty("hibernate.use_sql_comments",String.valueOf(hibernatePropertes.getUseSqlComments())); 65 | properties.setProperty("hibernate.dialect",String.valueOf(hibernatePropertes.getDialect())); 66 | properties.setProperty("hibernate.use_outer_join",String.valueOf(hibernatePropertes.isUseOuterJoin())); 67 | properties.setProperty("hibernate.query.factory_class",String.valueOf(hibernatePropertes.getQuery().getFactoryClass())); 68 | properties.setProperty("hibernate.format_sql",String.valueOf(hibernatePropertes.isShowSql())); 69 | properties.setProperty("hibernate.hbm2ddl.auto",String.valueOf(hibernatePropertes.getHbm2ddl())); 70 | properties.setProperty("hibernate.query.substitutions",String.valueOf(hibernatePropertes.getQuery().getSubstitutions())); 71 | properties.setProperty("hibernate.query.jpaql_strict_compliance",String.valueOf(hibernatePropertes.getQuery().isJpaqlStrictCompliance())); 72 | properties.setProperty("hibernate.jdbc.fetch_size",String.valueOf(hibernatePropertes.getJdbc().getFetchSize())); 73 | properties.setProperty("hibernate.jdbc.batch_size",String.valueOf(hibernatePropertes.getJdbc().getBatchSize())); 74 | properties.setProperty("hibernate.jdbc.sql_exception_converter",String.valueOf(hibernatePropertes.getJdbc().getSqlExceptionConverter())); 75 | properties.setProperty("hibernate.jdbc.wrap_result_sets",String.valueOf(hibernatePropertes.getJdbc().isWrapResultSets())); 76 | properties.setProperty("hibernate.jdbc.use_streams_for_binary",String.valueOf(hibernatePropertes.getJdbc().isUseStreamsForBinary())); 77 | properties.setProperty("hibernate.jdbc.use_scrollable_resultset",String.valueOf(hibernatePropertes.getJdbc().isUseScrollableResultset())); 78 | properties.setProperty("hibernate.jdbc.factory_class",String.valueOf(hibernatePropertes.getJdbc().getFactoryClass())); 79 | properties.setProperty("hibernate.jdbc.use_get_generated_keys",String.valueOf(hibernatePropertes.getJdbc().isUseGetGeneratedKeys())); 80 | properties.setProperty("hibernate.cache.jndi",String.valueOf(hibernatePropertes.getCache().isJndi())); 81 | properties.setProperty("hibernate.cache.use_second_level_cache",String.valueOf(hibernatePropertes.getCache().isUseSecondLevelCache())); 82 | properties.setProperty("hibernate.cache.use_structured_entries",String.valueOf(hibernatePropertes.getCache().isUseStructuredEntries())); 83 | properties.setProperty("hibernate.cache.use_query_cache",String.valueOf(hibernatePropertes.getCache().isUseStructuredEntries())); 84 | properties.setProperty("hibernate.cache.use_minimal_puts",String.valueOf(hibernatePropertes.getCache().isUseQueryCache())); 85 | properties.setProperty("hibernate.cache.provider_class",String.valueOf(hibernatePropertes.getCache().getProviderClass())); 86 | properties.setProperty("hibernate.cache.provider_configuration_file_resource_path",String.valueOf(hibernatePropertes.getCache().getProviderConfigurationFileResourcePath())); 87 | properties.setProperty("hibernate.cache.query_cache_factory",String.valueOf(hibernatePropertes.getCache().getQueryCacheFactory())); 88 | properties.setProperty("hibernate.cache.region_prefix",String.valueOf(hibernatePropertes.getCache().getRegionPrefix())); 89 | 90 | sessionFactory.setHibernateProperties(properties); 91 | sessionFactory.setPackagesToScan(hibernatePropertes.getPackagesToScan()); 92 | sessionFactory.setDataSource(dataSource); 93 | return sessionFactory; 94 | } 95 | 96 | @Bean(name = "transactionManager") 97 | @ConditionalOnMissingBean 98 | public HibernateTransactionManager setHibernateTransactionManager(SessionFactory sessionFactory){ 99 | HibernateTransactionManager transactionManager = new HibernateTransactionManager(); 100 | transactionManager.setSessionFactory(sessionFactory); 101 | return transactionManager; 102 | } 103 | 104 | } 105 | -------------------------------------------------------------------------------- /spring-boot-with-hibernate/src/main/java/cn/kiiwii/framework/hibernate/conf/DruidDataSourceProperties.java: -------------------------------------------------------------------------------- 1 | package cn.kiiwii.framework.hibernate.conf; 2 | 3 | import org.springframework.boot.context.properties.ConfigurationProperties; 4 | 5 | /** 6 | * Created by zhong on 2017/1/7. 7 | */ 8 | @ConfigurationProperties(prefix = "spring.datasource.druid") 9 | public class DruidDataSourceProperties { 10 | 11 | private String driverClassName; 12 | private String url; 13 | private String username; 14 | private String password; 15 | 16 | private int initialSize; 17 | private int minIdle; 18 | private int maxActive; 19 | private long maxWait; 20 | private long timeBetweenEvictionRunsMillis; 21 | private long minEvictableIdleTimeMillis; 22 | private String validationQuery; 23 | private boolean testWhileIdle; 24 | private boolean testOnBorrow; 25 | private boolean testOnReturn; 26 | private boolean poolPreparedStatements; 27 | private int maxPoolPreparedStatementPerConnectionSize; 28 | private String filters; 29 | private String connectionProperties; 30 | 31 | public int getInitialSize() { 32 | return initialSize; 33 | } 34 | 35 | public void setInitialSize(int initialSize) { 36 | this.initialSize = initialSize; 37 | } 38 | 39 | public int getMinIdle() { 40 | return minIdle; 41 | } 42 | 43 | public void setMinIdle(int minIdle) { 44 | this.minIdle = minIdle; 45 | } 46 | 47 | public int getMaxActive() { 48 | return maxActive; 49 | } 50 | 51 | public void setMaxActive(int maxActive) { 52 | this.maxActive = maxActive; 53 | } 54 | 55 | public long getMaxWait() { 56 | return maxWait; 57 | } 58 | 59 | public void setMaxWait(long maxWait) { 60 | this.maxWait = maxWait; 61 | } 62 | 63 | public long getTimeBetweenEvictionRunsMillis() { 64 | return timeBetweenEvictionRunsMillis; 65 | } 66 | 67 | public void setTimeBetweenEvictionRunsMillis(long timeBetweenEvictionRunsMillis) { 68 | this.timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis; 69 | } 70 | 71 | public long getMinEvictableIdleTimeMillis() { 72 | return minEvictableIdleTimeMillis; 73 | } 74 | 75 | public void setMinEvictableIdleTimeMillis(long minEvictableIdleTimeMillis) { 76 | this.minEvictableIdleTimeMillis = minEvictableIdleTimeMillis; 77 | } 78 | 79 | public String getValidationQuery() { 80 | return validationQuery; 81 | } 82 | 83 | public void setValidationQuery(String validationQuery) { 84 | this.validationQuery = validationQuery; 85 | } 86 | 87 | public boolean isTestWhileIdle() { 88 | return testWhileIdle; 89 | } 90 | 91 | public void setTestWhileIdle(boolean testWhileIdle) { 92 | this.testWhileIdle = testWhileIdle; 93 | } 94 | 95 | public boolean isTestOnBorrow() { 96 | return testOnBorrow; 97 | } 98 | 99 | public void setTestOnBorrow(boolean testOnBorrow) { 100 | this.testOnBorrow = testOnBorrow; 101 | } 102 | 103 | public boolean isTestOnReturn() { 104 | return testOnReturn; 105 | } 106 | 107 | public void setTestOnReturn(boolean testOnReturn) { 108 | this.testOnReturn = testOnReturn; 109 | } 110 | 111 | public boolean isPoolPreparedStatements() { 112 | return poolPreparedStatements; 113 | } 114 | 115 | public void setPoolPreparedStatements(boolean poolPreparedStatements) { 116 | this.poolPreparedStatements = poolPreparedStatements; 117 | } 118 | 119 | public int getMaxPoolPreparedStatementPerConnectionSize() { 120 | return maxPoolPreparedStatementPerConnectionSize; 121 | } 122 | 123 | public void setMaxPoolPreparedStatementPerConnectionSize(int maxPoolPreparedStatementPerConnectionSize) { 124 | this.maxPoolPreparedStatementPerConnectionSize = maxPoolPreparedStatementPerConnectionSize; 125 | } 126 | 127 | public String getFilters() { 128 | return filters; 129 | } 130 | 131 | public void setFilters(String filters) { 132 | this.filters = filters; 133 | } 134 | 135 | public String getConnectionProperties() { 136 | return connectionProperties; 137 | } 138 | 139 | public void setConnectionProperties(String connectionProperties) { 140 | this.connectionProperties = connectionProperties; 141 | } 142 | 143 | public String getDriverClassName() { 144 | return driverClassName; 145 | } 146 | 147 | public void setDriverClassName(String driverClassName) { 148 | this.driverClassName = driverClassName; 149 | } 150 | 151 | public String getUrl() { 152 | return url; 153 | } 154 | 155 | public void setUrl(String url) { 156 | this.url = url; 157 | } 158 | 159 | public String getUsername() { 160 | return username; 161 | } 162 | 163 | public void setUsername(String username) { 164 | this.username = username; 165 | } 166 | 167 | public String getPassword() { 168 | return password; 169 | } 170 | 171 | public void setPassword(String password) { 172 | this.password = password; 173 | } 174 | 175 | } 176 | -------------------------------------------------------------------------------- /spring-boot-with-hibernate/src/main/java/cn/kiiwii/framework/hibernate/controller/TestController.java: -------------------------------------------------------------------------------- 1 | package cn.kiiwii.framework.hibernate.controller; 2 | 3 | import cn.kiiwii.framework.hibernate.service.ITestService; 4 | import org.slf4j.Logger; 5 | import org.slf4j.LoggerFactory; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.stereotype.Controller; 8 | import org.springframework.web.bind.annotation.RequestMapping; 9 | import org.springframework.web.bind.annotation.RestController; 10 | 11 | /** 12 | * Created by zhong on 2016/11/10. 13 | */ 14 | @RestController 15 | @Controller 16 | public class TestController { 17 | @Autowired 18 | private ITestService testService; 19 | private Logger logger = LoggerFactory.getLogger(this.getClass()); 20 | 21 | @RequestMapping("/test") 22 | public String greeting() { 23 | testService.test(); 24 | return "hello"; 25 | } 26 | 27 | @RequestMapping("/testTrans") 28 | public String testTrans() { 29 | try { 30 | testService.testTransaction(); 31 | } catch (Exception e) { 32 | e.printStackTrace(); 33 | } 34 | return "testTransaction"; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /spring-boot-with-hibernate/src/main/java/cn/kiiwii/framework/hibernate/dao/ITestDAO.java: -------------------------------------------------------------------------------- 1 | package cn.kiiwii.framework.hibernate.dao; 2 | 3 | /** 4 | * Created by zhong on 2016/9/5. 5 | */ 6 | public interface ITestDAO { 7 | void test(); 8 | 9 | void save(Object o); 10 | } 11 | -------------------------------------------------------------------------------- /spring-boot-with-hibernate/src/main/java/cn/kiiwii/framework/hibernate/dao/impl/TestDAOImpl.java: -------------------------------------------------------------------------------- 1 | package cn.kiiwii.framework.hibernate.dao.impl; 2 | 3 | import cn.kiiwii.framework.hibernate.dao.ITestDAO; 4 | import cn.kiiwii.framework.hibernate.model.SpringBootWithHinernateTest; 5 | import org.hibernate.SessionFactory; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.beans.factory.annotation.Qualifier; 8 | import org.springframework.jdbc.core.JdbcTemplate; 9 | import org.springframework.orm.hibernate4.support.HibernateDaoSupport; 10 | import org.springframework.stereotype.Repository; 11 | 12 | import java.util.List; 13 | import java.util.Map; 14 | 15 | /** 16 | * Created by zhong on 2016/9/5. 17 | */ 18 | @Repository("testDAO") 19 | public class TestDAOImpl extends HibernateDaoSupport implements ITestDAO { 20 | 21 | @Autowired 22 | public void setMySessionFactory(SessionFactory sessionFactory) { 23 | super.setSessionFactory(sessionFactory); 24 | } 25 | 26 | @Override 27 | public void test() { 28 | SpringBootWithHinernateTest springBootWithHinernateTest = this.getHibernateTemplate().get(SpringBootWithHinernateTest.class,1); 29 | System.out.println(springBootWithHinernateTest); 30 | } 31 | 32 | @Override 33 | public void save(Object o) { 34 | this.getHibernateTemplate().save(o); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /spring-boot-with-hibernate/src/main/java/cn/kiiwii/framework/hibernate/model/SpringBootWithHinernateTest.java: -------------------------------------------------------------------------------- 1 | package cn.kiiwii.framework.hibernate.model; 2 | 3 | import org.hibernate.annotations.Generated; 4 | import org.hibernate.annotations.GenerationTime; 5 | 6 | import javax.persistence.*; 7 | import java.io.Serializable; 8 | import java.sql.Timestamp; 9 | import java.util.Date; 10 | 11 | /** 12 | * Created by zhong on 2017/1/5. 13 | */ 14 | @Table(name = "spring_boot_with_hinernate_test") 15 | @Entity 16 | public class SpringBootWithHinernateTest implements Serializable{ 17 | 18 | @Id 19 | @GeneratedValue(strategy = GenerationType.AUTO) 20 | @Column(name = "id") 21 | private Integer id; 22 | @Column(name = "user_name",length = 128) 23 | private String userName; 24 | @Column(name = "create_time") 25 | private Timestamp createTime; 26 | 27 | public SpringBootWithHinernateTest() { 28 | } 29 | 30 | public SpringBootWithHinernateTest(String userName, Timestamp createTime) { 31 | this.userName = userName; 32 | this.createTime = createTime; 33 | } 34 | 35 | public Integer getId() { 36 | return id; 37 | } 38 | 39 | public void setId(Integer id) { 40 | this.id = id; 41 | } 42 | 43 | public String getUserName() { 44 | return userName; 45 | } 46 | 47 | public void setUserName(String userName) { 48 | this.userName = userName; 49 | } 50 | 51 | public Timestamp getCreateTime() { 52 | return createTime; 53 | } 54 | 55 | public void setCreateTime(Timestamp createTime) { 56 | this.createTime = createTime; 57 | } 58 | 59 | @Override 60 | public String toString() { 61 | return "SpringBootWithHinernateTest{" + 62 | "id=" + id + 63 | ", userName='" + userName + '\'' + 64 | ", createTime=" + createTime + 65 | '}'; 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /spring-boot-with-hibernate/src/main/java/cn/kiiwii/framework/hibernate/model/SpringBootWithHinernateTest2.java: -------------------------------------------------------------------------------- 1 | package cn.kiiwii.framework.hibernate.model; 2 | 3 | import javax.persistence.*; 4 | import java.io.Serializable; 5 | import java.sql.Timestamp; 6 | 7 | /** 8 | * Created by zhong on 2017/1/5. 9 | */ 10 | @Table(name = "spring_boot_with_hinernate_test2") 11 | @Entity 12 | public class SpringBootWithHinernateTest2 implements Serializable{ 13 | 14 | @Id 15 | @GeneratedValue(strategy = GenerationType.AUTO) 16 | @Column(name = "id") 17 | private Integer id; 18 | @Column(name = "user_name",length = 128) 19 | private String userName; 20 | @Column(name = "create_time") 21 | private Timestamp createTime; 22 | 23 | public SpringBootWithHinernateTest2() { 24 | } 25 | 26 | public SpringBootWithHinernateTest2(String userName, Timestamp createTime) { 27 | this.userName = userName; 28 | this.createTime = createTime; 29 | } 30 | 31 | public Integer getId() { 32 | return id; 33 | } 34 | 35 | public void setId(Integer id) { 36 | this.id = id; 37 | } 38 | 39 | public String getUserName() { 40 | return userName; 41 | } 42 | 43 | public void setUserName(String userName) { 44 | this.userName = userName; 45 | } 46 | 47 | public Timestamp getCreateTime() { 48 | return createTime; 49 | } 50 | 51 | public void setCreateTime(Timestamp createTime) { 52 | this.createTime = createTime; 53 | } 54 | 55 | @Override 56 | public String toString() { 57 | return "SpringBootWithHinernateTest{" + 58 | "id=" + id + 59 | ", userName='" + userName + '\'' + 60 | ", createTime=" + createTime + 61 | '}'; 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /spring-boot-with-hibernate/src/main/java/cn/kiiwii/framework/hibernate/service/ITestService.java: -------------------------------------------------------------------------------- 1 | package cn.kiiwii.framework.hibernate.service; 2 | 3 | /** 4 | * Created by zhong on 2017/1/5. 5 | */ 6 | public interface ITestService { 7 | void test(); 8 | 9 | void testTransaction() throws Exception; 10 | } 11 | -------------------------------------------------------------------------------- /spring-boot-with-hibernate/src/main/java/cn/kiiwii/framework/hibernate/service/impl/TestServiceImpl.java: -------------------------------------------------------------------------------- 1 | package cn.kiiwii.framework.hibernate.service.impl; 2 | 3 | import cn.kiiwii.framework.hibernate.dao.ITestDAO; 4 | import cn.kiiwii.framework.hibernate.model.SpringBootWithHinernateTest; 5 | import cn.kiiwii.framework.hibernate.model.SpringBootWithHinernateTest2; 6 | import cn.kiiwii.framework.hibernate.service.ITestService; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.stereotype.Service; 9 | import org.springframework.transaction.annotation.Propagation; 10 | import org.springframework.transaction.annotation.Transactional; 11 | 12 | /** 13 | * Created by zhong on 2016/9/5. 14 | */ 15 | @Service("testService") 16 | public class TestServiceImpl implements ITestService { 17 | 18 | @Autowired 19 | ITestDAO testDAO; 20 | 21 | @Override 22 | public void test() { 23 | this.testDAO.test(); 24 | } 25 | 26 | @Transactional(propagation = Propagation.REQUIRED) 27 | @Override 28 | public void testTransaction() throws Exception{ 29 | SpringBootWithHinernateTest springBootWithHinernateTest = new SpringBootWithHinernateTest(); 30 | springBootWithHinernateTest.setUserName("zhonglin1"); 31 | this.testDAO.save(springBootWithHinernateTest); 32 | int i = 9 / 0; 33 | SpringBootWithHinernateTest2 springBootWithHinernateTest2 = new SpringBootWithHinernateTest2(); 34 | springBootWithHinernateTest2.setUserName("zhonglin2"); 35 | this.testDAO.save(springBootWithHinernateTest2); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /spring-boot-with-hibernate/src/main/resources/application.properties: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhonglinlin1305/spring-boot-sample/efd45c9948a0e4e8379698dbb421852d291f4c45/spring-boot-with-hibernate/src/main/resources/application.properties -------------------------------------------------------------------------------- /spring-boot-with-hibernate/src/main/resources/log4j.properties: -------------------------------------------------------------------------------- 1 | log4j.rootLogger=INFO,CONSOLE,ROLLING_FILE 2 | 3 | ################## 4 | #Console Appender 5 | ################## 6 | log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender 7 | log4j.appender.Threshold=INFO 8 | log4j.appender.CONSOLE.Target=System.out 9 | log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout 10 | log4j.appender.CONSOLE.layout.ConversionPattern= [%p] %d %c - %m%n 11 | 12 | ######################## 13 | # Rolling File 14 | ######################## 15 | log4j.appender.ROLLING_FILE=org.apache.log4j.DailyRollingFileAppender 16 | log4j.appender.ROLLING_FILE.Threshold=INFO 17 | log4j.appender.ROLLING_FILE.File=../logs/hibernate/consol.log 18 | log4j.appender.ROLLING_FILE.Append=true 19 | log4j.appender.ROLLING_FILE.layout=org.apache.log4j.PatternLayout 20 | log4j.appender.ROLLING_FILE.layout.ConversionPattern=%d{yyyy-M-d HH:mm:ss}%x[%5p](%F:%L) %m%n -------------------------------------------------------------------------------- /spring-boot-with-hibernate/src/main/script/init.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE `spring_boot_with_hinernate_test` ( 2 | `id` int(11) NOT NULL AUTO_INCREMENT, 3 | `create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP, 4 | `user_name` varchar(128) DEFAULT NULL, 5 | PRIMARY KEY (`id`) 6 | ) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8; 7 | 8 | CREATE TABLE `spring_boot_with_hinernate_test2` ( 9 | `id` int(11) NOT NULL AUTO_INCREMENT, 10 | `create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP, 11 | `user_name` varchar(128) DEFAULT NULL, 12 | PRIMARY KEY (`id`) 13 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -------------------------------------------------------------------------------- /spring-boot-with-jpa/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | spring-boot-sample 7 | cn.kiiwii.framework 8 | 1.0-SNAPSHOT 9 | 10 | 4.0.0 11 | 12 | spring-boot-with-jpa 13 | 14 | 15 | 16 | junit 17 | junit 18 | 4.12 19 | test 20 | 21 | 22 | org.springframework.boot 23 | spring-boot-starter-web 24 | 25 | 26 | org.springframework.boot 27 | spring-boot-starter 28 | 29 | 30 | org.springframework.boot 31 | spring-boot-starter-logging 32 | 33 | 34 | 35 | 36 | org.springframework.boot 37 | spring-boot-configuration-processor 38 | true 39 | 40 | 41 | org.springframework.boot 42 | spring-boot-starter-jdbc 43 | 44 | 45 | org.springframework.boot 46 | spring-boot-starter-jdbc 47 | 48 | 49 | org.springframework.boot 50 | spring-boot-starter-log4j 51 | 1.3.7.RELEASE 52 | 53 | 54 | mysql 55 | mysql-connector-java 56 | 5.1.38 57 | 58 | 59 | com.alibaba 60 | druid 61 | 1.0.25 62 | 63 | 64 | org.springframework 65 | spring-context 66 | 4.3.2.RELEASE 67 | 68 | 69 | org.springframework 70 | spring-orm 71 | 4.3.2.RELEASE 72 | 73 | 74 | org.springframework.boot 75 | spring-boot-starter-data-jpa 76 | 77 | 78 | org.hibernate 79 | hibernate-core 80 | 4.3.7.Final 81 | 82 | 83 | org.hibernate 84 | hibernate-core 85 | 5.0.6.Final 86 | 87 | 88 | 89 | 90 | 91 | 92 | org.apache.maven.plugins 93 | maven-compiler-plugin 94 | 3.2 95 | 96 | 1.7 97 | 1.7 98 | 99 | 100 | 101 | org.springframework.boot 102 | spring-boot-maven-plugin 103 | 104 | 105 | 106 | repackage 107 | 108 | 109 | 110 | 111 | 112 | 113 | -------------------------------------------------------------------------------- /spring-boot-with-jpa/src/main/java/cn/kiiwii/framework/Application.java: -------------------------------------------------------------------------------- 1 | package cn.kiiwii.framework; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.EnableAutoConfiguration; 5 | import org.springframework.boot.autoconfigure.domain.EntityScan; 6 | import org.springframework.context.annotation.ComponentScan; 7 | import org.springframework.context.annotation.Configuration; 8 | import org.springframework.data.jpa.repository.config.EnableJpaRepositories; 9 | 10 | /** 11 | * Created by zhong on 2016/11/24. 12 | */ 13 | @Configuration 14 | @ComponentScan(basePackages="cn.kiiwii.framework") 15 | @EnableAutoConfiguration 16 | @EntityScan(basePackages="cn.kiiwii.framework.model") 17 | @EnableJpaRepositories(basePackages="cn.kiiwii.framework.dao") 18 | public class Application { 19 | public static void main(String[] args) { 20 | SpringApplication.run(Application.class, args); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /spring-boot-with-jpa/src/main/java/cn/kiiwii/framework/controller/TestController.java: -------------------------------------------------------------------------------- 1 | package cn.kiiwii.framework.controller; 2 | 3 | import cn.kiiwii.framework.service.ITestService; 4 | import org.slf4j.Logger; 5 | import org.slf4j.LoggerFactory; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.stereotype.Controller; 8 | import org.springframework.web.bind.annotation.RequestMapping; 9 | import org.springframework.web.bind.annotation.RestController; 10 | 11 | /** 12 | * Created by zhong on 2016/11/10. 13 | */ 14 | @RestController 15 | @Controller 16 | public class TestController { 17 | @Autowired 18 | private ITestService testService; 19 | private Logger logger = LoggerFactory.getLogger(this.getClass()); 20 | 21 | @RequestMapping("/test") 22 | public String greeting() { 23 | testService.test(); 24 | return "hello"; 25 | } 26 | 27 | @RequestMapping("/testTrans") 28 | public String testTrans() { 29 | testService.testTransaction(); 30 | return "testTransaction"; 31 | } 32 | @RequestMapping("/testJpa") 33 | public String testJpa() { 34 | testService.testJpa(); 35 | return "testTransaction"; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /spring-boot-with-jpa/src/main/java/cn/kiiwii/framework/dao/ITestDAO.java: -------------------------------------------------------------------------------- 1 | package cn.kiiwii.framework.dao; 2 | 3 | /** 4 | * Created by zhong on 2016/9/5. 5 | */ 6 | public interface ITestDAO { 7 | void test(); 8 | 9 | void save(); 10 | } 11 | -------------------------------------------------------------------------------- /spring-boot-with-jpa/src/main/java/cn/kiiwii/framework/dao/TestRepository.java: -------------------------------------------------------------------------------- 1 | package cn.kiiwii.framework.dao; 2 | 3 | import cn.kiiwii.framework.model.Test; 4 | import org.springframework.beans.factory.annotation.Qualifier; 5 | import org.springframework.data.domain.Example; 6 | import org.springframework.data.domain.Page; 7 | import org.springframework.data.domain.Pageable; 8 | import org.springframework.data.domain.Sort; 9 | import org.springframework.data.jpa.repository.JpaRepository; 10 | import org.springframework.data.jpa.repository.Query; 11 | import org.springframework.data.jpa.repository.support.JpaEntityInformation; 12 | import org.springframework.data.jpa.repository.support.SimpleJpaRepository; 13 | import org.springframework.data.repository.CrudRepository; 14 | import org.springframework.data.repository.query.Param; 15 | import org.springframework.stereotype.Repository; 16 | 17 | import javax.persistence.EntityManager; 18 | import javax.persistence.Table; 19 | import java.io.Serializable; 20 | import java.util.List; 21 | 22 | /** 23 | * Created by zhong on 2016/11/24. 24 | */ 25 | @Repository 26 | @Table(name="test") 27 | @Qualifier("testRepository") 28 | public interface TestRepository extends JpaRepository { 29 | 30 | @Query(" from Test t where t.testName=:testName") 31 | List findUser(@Param("testName") String testName); 32 | } 33 | -------------------------------------------------------------------------------- /spring-boot-with-jpa/src/main/java/cn/kiiwii/framework/druid/DruidConfiguration.java: -------------------------------------------------------------------------------- 1 | package cn.kiiwii.framework.druid; 2 | 3 | import com.alibaba.druid.pool.DruidDataSource; 4 | import com.alibaba.druid.support.http.StatViewServlet; 5 | import com.alibaba.druid.support.http.WebStatFilter; 6 | import org.springframework.beans.factory.annotation.Value; 7 | import org.springframework.boot.web.servlet.FilterRegistrationBean; 8 | import org.springframework.boot.web.servlet.ServletRegistrationBean; 9 | import org.springframework.context.annotation.Bean; 10 | import org.springframework.context.annotation.Configuration; 11 | 12 | import javax.sql.DataSource; 13 | import java.sql.SQLException; 14 | 15 | /** 16 | * Created by zhong on 2016/9/5. 17 | */ 18 | @Configuration 19 | public class DruidConfiguration { 20 | @Value("${spring.datasource.driverClassName}") 21 | private String driver; 22 | @Value("${spring.datasource.url}") 23 | String url; 24 | @Value("${spring.datasource.username}") 25 | String username; 26 | @Value("${spring.datasource.password}") 27 | String password; 28 | @Value("${spring.datasource.initialSize}") 29 | int initialSize; 30 | @Value("${spring.datasource.minIdle}") 31 | int minIdle; 32 | @Value("${spring.datasource.maxActive}") 33 | int maxActive; 34 | @Value("${spring.datasource.maxWait}") 35 | long maxWait; 36 | @Value("${spring.datasource.timeBetweenEvictionRunsMillis}") 37 | long timeBetweenEvictionRunsMillis; 38 | @Value("${spring.datasource.minEvictableIdleTimeMillis}") 39 | long minEvictableIdleTimeMillis; 40 | @Value("${spring.datasource.validationQuery}") 41 | String validationQuery; 42 | @Value("${spring.datasource.testWhileIdle}") 43 | boolean testWhileIdle; 44 | @Value("${spring.datasource.testOnBorrow}") 45 | boolean testOnBorrow; 46 | @Value("${spring.datasource.testOnReturn}") 47 | boolean testOnReturn; 48 | @Value("${spring.datasource.poolPreparedStatements}") 49 | boolean poolPreparedStatements; 50 | @Value("${spring.datasource.maxPoolPreparedStatementPerConnectionSize}") 51 | int maxPoolPreparedStatementPerConnectionSize; 52 | @Value("${spring.datasource.filters}") 53 | String filters; 54 | @Value("${spring.datasource.connectionProperties}") 55 | String connectionProperties; 56 | 57 | @Bean 58 | public DataSource druidDataSource() { 59 | DruidDataSource druidDataSource = new DruidDataSource(); 60 | druidDataSource.setDriverClassName(driver); 61 | druidDataSource.setUrl(url); 62 | druidDataSource.setUsername(username); 63 | druidDataSource.setPassword(password); 64 | druidDataSource.setInitialSize(initialSize); 65 | druidDataSource.setMinIdle(minIdle); 66 | druidDataSource.setMaxActive(maxActive); 67 | druidDataSource.setMaxWait(maxWait); 68 | druidDataSource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis); 69 | druidDataSource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis); 70 | druidDataSource.setValidationQuery(validationQuery); 71 | druidDataSource.setTestWhileIdle(testWhileIdle); 72 | druidDataSource.setTestOnBorrow(testOnBorrow); 73 | druidDataSource.setTestOnReturn(testOnReturn); 74 | druidDataSource.setPoolPreparedStatements(poolPreparedStatements); 75 | druidDataSource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize); 76 | druidDataSource.setConnectionProperties(connectionProperties); 77 | try { 78 | druidDataSource.setFilters(filters); 79 | druidDataSource.init(); 80 | } catch (SQLException e) { 81 | e.printStackTrace(); 82 | } 83 | 84 | return druidDataSource; 85 | } 86 | 87 | @Bean 88 | public ServletRegistrationBean druidServlet() { 89 | 90 | ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*"); 91 | 92 | //添加初始化参数:initParams 93 | 94 | //白名单: 95 | //servletRegistrationBean.addInitParameter("allow","127.0.0.1"); 96 | //IP黑名单 (存在共同时,deny优先于allow) : 如果满足deny的话提示:Sorry, you are not permitted to view this page. 97 | //servletRegistrationBean.addInitParameter("deny","192.168.1.73"); 98 | //登录查看信息的账号密码. 99 | servletRegistrationBean.addInitParameter("loginUsername", "admin"); 100 | servletRegistrationBean.addInitParameter("loginPassword", "admin"); 101 | //是否能够重置数据. 102 | servletRegistrationBean.addInitParameter("resetEnable", "true"); 103 | return servletRegistrationBean; 104 | 105 | } 106 | 107 | @Bean 108 | public FilterRegistrationBean filterRegistrationBean() { 109 | FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(); 110 | filterRegistrationBean.setFilter(new WebStatFilter()); 111 | filterRegistrationBean.addUrlPatterns("/*"); 112 | filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*"); 113 | return filterRegistrationBean; 114 | } 115 | } 116 | -------------------------------------------------------------------------------- /spring-boot-with-jpa/src/main/java/cn/kiiwii/framework/model/Test.java: -------------------------------------------------------------------------------- 1 | package cn.kiiwii.framework.model; 2 | 3 | import javax.persistence.*; 4 | import java.io.Serializable; 5 | import java.sql.Timestamp; 6 | 7 | /** 8 | * Created by zhong on 2016/11/24. 9 | */ 10 | @Entity 11 | @Table(name = "test") 12 | public class Test implements Serializable{ 13 | @Id 14 | @GeneratedValue 15 | @Column(name = "id") 16 | private Integer id; 17 | @Column(name = "test_name") 18 | private String testName; 19 | @Column(name = "test_num") 20 | private Integer testNum; 21 | @Column(name = "test_time") 22 | private Timestamp testTime; 23 | 24 | public Integer getId() { 25 | return id; 26 | } 27 | 28 | public void setId(Integer id) { 29 | this.id = id; 30 | } 31 | 32 | public String getTestName() { 33 | return testName; 34 | } 35 | 36 | public void setTestName(String testName) { 37 | this.testName = testName; 38 | } 39 | 40 | public Integer getTestNum() { 41 | return testNum; 42 | } 43 | 44 | public void setTestNum(Integer testNum) { 45 | this.testNum = testNum; 46 | } 47 | 48 | public Timestamp getTestTime() { 49 | return testTime; 50 | } 51 | 52 | public void setTestTime(Timestamp testTime) { 53 | this.testTime = testTime; 54 | } 55 | 56 | @Override 57 | public String toString() { 58 | return "Test{" + 59 | "id=" + id + 60 | ", testName='" + testName + '\'' + 61 | ", testNum=" + testNum + 62 | ", testTime=" + testTime + 63 | '}'; 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /spring-boot-with-jpa/src/main/resources/application.properties: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhonglinlin1305/spring-boot-sample/efd45c9948a0e4e8379698dbb421852d291f4c45/spring-boot-with-jpa/src/main/resources/application.properties -------------------------------------------------------------------------------- /spring-boot-with-jpa/src/main/resources/log4j.properties: -------------------------------------------------------------------------------- 1 | log4j.rootLogger=INFO,CONSOLE,ROLLING_FILE 2 | 3 | ################## 4 | #Console Appender 5 | ################## 6 | log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender 7 | log4j.appender.Threshold=INFO 8 | log4j.appender.CONSOLE.Target=System.out 9 | log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout 10 | log4j.appender.CONSOLE.layout.ConversionPattern= [%p] %d %c - %m%n 11 | 12 | ######################## 13 | # Rolling File 14 | ######################## 15 | log4j.appender.ROLLING_FILE=org.apache.log4j.DailyRollingFileAppender 16 | log4j.appender.ROLLING_FILE.Threshold=INFO 17 | log4j.appender.ROLLING_FILE.File=../logs/schedule/consol.log 18 | log4j.appender.ROLLING_FILE.Append=true 19 | log4j.appender.ROLLING_FILE.layout=org.apache.log4j.PatternLayout 20 | log4j.appender.ROLLING_FILE.layout.ConversionPattern=%d{yyyy-M-d HH:mm:ss}%x[%5p](%F:%L) %m%n -------------------------------------------------------------------------------- /spring-boot-with-jpa/src/main/script/test.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE `test` ( 2 | `id` int(11) NOT NULL AUTO_INCREMENT, 3 | `test_name` varchar(45) DEFAULT NULL, 4 | `test_num` int(11) DEFAULT '0', 5 | `test_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP, 6 | PRIMARY KEY (`id`) 7 | ) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8; -------------------------------------------------------------------------------- /spring-boot-with-mybatis/README.md: -------------------------------------------------------------------------------- 1 | #spring-boot 整合mybatis 2 | 本系列是spring-boot相关的一些列子,比如spring-boot集成druid,以及druid的动态数据源切换, 3 | spring-boot 集成mybatis,spring-boot集成定时器等等 4 | 5 | 1、在pom文件中添加mybatis的依赖 6 | 7 | 8 | org.mybatis.spring.boot 9 | mybatis-spring-boot-starter 10 | 1.1.1 11 | 12 | 13 | mysql 14 | mysql-connector-java 15 | 5.1.38 16 | 17 | 18 | 2、在配置文件中添加mybatis设置 19 | 20 | mybatis.type-aliases-package=cn.kiiwii.framework.mybatis.model 21 | mybatis.mapper-locations=classpath:cn/kiiwii/framework/mybatis/mapping/*.xml 22 | 23 | 3、在Application添加扫描注解 24 | 25 | @MapperScan("cn.kiiwii.framework.mybatis.mapper") -------------------------------------------------------------------------------- /spring-boot-with-mybatis/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | spring-boot-sample 7 | cn.kiiwii.framework 8 | 1.0-SNAPSHOT 9 | 10 | 4.0.0 11 | 12 | spring-boot-with-mybatis 13 | 14 | 15 | junit 16 | junit 17 | 4.12 18 | test 19 | 20 | 21 | org.springframework.boot 22 | spring-boot-starter-web 23 | 24 | 25 | org.springframework.boot 26 | spring-boot-starter 27 | 28 | 29 | org.springframework.boot 30 | spring-boot-starter-logging 31 | 32 | 33 | 34 | 35 | org.springframework.boot 36 | spring-boot-starter-log4j 37 | 1.3.7.RELEASE 38 | 39 | 40 | org.springframework.boot 41 | spring-boot-configuration-processor 42 | true 43 | 44 | 45 | org.springframework.boot 46 | spring-boot-starter-aop 47 | 48 | 49 | org.springframework.boot 50 | spring-boot-test 51 | 52 | 53 | org.springframework.boot 54 | spring-boot-starter-test 55 | 56 | 57 | org.mybatis.spring.boot 58 | mybatis-spring-boot-starter 59 | 1.1.1 60 | 61 | 62 | mysql 63 | mysql-connector-java 64 | 5.1.38 65 | 66 | 67 | com.alibaba 68 | druid 69 | 1.0.25 70 | 71 | 72 | 73 | org.springframework.boot 74 | spring-boot-starter-tomcat 75 | provided 76 | 77 | 78 | org.apache.tomcat.embed 79 | tomcat-embed-jasper 80 | 7.0.70 81 | 82 | 83 | javax.servlet 84 | jstl 85 | 86 | 87 | javax.servlet 88 | javax.servlet-api 89 | provided 90 | 91 | 92 | 93 | 94 | 95 | 96 | src/main/java 97 | 98 | **/*.xml 99 | 100 | 101 | 102 | 103 | 104 | org.apache.maven.plugins 105 | maven-compiler-plugin 106 | 3.2 107 | 108 | 1.7 109 | 1.7 110 | 111 | 112 | 113 | org.springframework.boot 114 | spring-boot-maven-plugin 115 | 116 | 117 | 118 | repackage 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | -------------------------------------------------------------------------------- /spring-boot-with-mybatis/src/main/java/cn/kiiwii/framework/mybatis/Application.java: -------------------------------------------------------------------------------- 1 | package cn.kiiwii.framework.mybatis; 2 | 3 | import org.mybatis.spring.annotation.MapperScan; 4 | import org.slf4j.Logger; 5 | import org.slf4j.LoggerFactory; 6 | import org.springframework.boot.SpringApplication; 7 | import org.springframework.boot.autoconfigure.EnableAutoConfiguration; 8 | import org.springframework.boot.autoconfigure.ImportAutoConfiguration; 9 | import org.springframework.boot.autoconfigure.SpringBootApplication; 10 | import org.springframework.boot.builder.SpringApplicationBuilder; 11 | import org.springframework.boot.web.support.SpringBootServletInitializer; 12 | import org.springframework.cache.annotation.EnableCaching; 13 | import org.springframework.context.annotation.ComponentScan; 14 | import org.springframework.transaction.annotation.EnableTransactionManagement; 15 | import org.springframework.web.bind.annotation.RestController; 16 | 17 | /** 18 | * Created by zhong on 2016/11/10. 19 | */ 20 | 21 | @EnableTransactionManagement//启动事务 22 | @SpringBootApplication 23 | @MapperScan("cn.kiiwii.framework.mybatis.mapper") 24 | public class Application extends SpringBootServletInitializer { 25 | 26 | static Logger logger = LoggerFactory.getLogger(Application.class); 27 | 28 | @Override 29 | protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { 30 | return application.sources(Application.class); 31 | } 32 | 33 | public static void main(String[] args) throws Exception { 34 | SpringApplication.run(Application.class, args); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /spring-boot-with-mybatis/src/main/java/cn/kiiwii/framework/mybatis/aop/ServiceAop.java: -------------------------------------------------------------------------------- 1 | package cn.kiiwii.framework.mybatis.aop; 2 | 3 | import org.aspectj.lang.JoinPoint; 4 | import org.aspectj.lang.ProceedingJoinPoint; 5 | import org.aspectj.lang.annotation.*; 6 | import org.slf4j.Logger; 7 | import org.slf4j.LoggerFactory; 8 | import org.springframework.stereotype.Component; 9 | import org.springframework.web.context.request.RequestContextHolder; 10 | import org.springframework.web.context.request.ServletRequestAttributes; 11 | 12 | import javax.servlet.http.HttpServletRequest; 13 | 14 | /** 15 | * Created by zhong on 2016/11/24. 16 | */ 17 | @Aspect 18 | @Component 19 | public class ServiceAop { 20 | private static Logger logger = LoggerFactory.getLogger(ServiceAop.class); 21 | 22 | private ThreadLocal timeLocal = new ThreadLocal(); 23 | 24 | @Pointcut("execution(public * cn.kiiwii.framework.mybatis.service.impl.*.*(..))") 25 | public void webRequestLog() {} 26 | 27 | @Before("webRequestLog()") 28 | public void doBefore(JoinPoint joinPoint) { 29 | timeLocal.set(System.currentTimeMillis()); 30 | } 31 | 32 | @AfterReturning(returning = "result", pointcut = "webRequestLog()") 33 | public void doAfterReturning(Object result) { 34 | long startTime = timeLocal.get(); 35 | logger.info("花费的时间为:"+(System.currentTimeMillis()-startTime)+"毫秒"); 36 | } 37 | 38 | @Around("webRequestLog()") 39 | public Object around(ProceedingJoinPoint pjp) throws Throwable { 40 | Object o = null; 41 | 42 | o = pjp.proceed(); 43 | 44 | return o; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /spring-boot-with-mybatis/src/main/java/cn/kiiwii/framework/mybatis/controller/TestController.java: -------------------------------------------------------------------------------- 1 | package cn.kiiwii.framework.mybatis.controller; 2 | 3 | import cn.kiiwii.framework.mybatis.model.Account; 4 | import cn.kiiwii.framework.mybatis.service.ITestService; 5 | import cn.kiiwii.framework.mybatis.service.ITestXmlService; 6 | import org.slf4j.Logger; 7 | import org.slf4j.LoggerFactory; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.stereotype.Controller; 10 | import org.springframework.web.bind.annotation.RequestMapping; 11 | import org.springframework.web.bind.annotation.ResponseBody; 12 | import org.springframework.web.bind.annotation.RestController; 13 | 14 | import javax.servlet.http.HttpServletRequest; 15 | import javax.servlet.http.HttpServletResponse; 16 | import java.util.List; 17 | 18 | /** 19 | * Created by zhong on 2016/11/10. 20 | */ 21 | @RestController 22 | @Controller 23 | public class TestController { 24 | private org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(TestController.class); 25 | @Autowired 26 | private ITestService testService; 27 | 28 | @Autowired 29 | private ITestXmlService testXmlService; 30 | 31 | @ResponseBody 32 | @RequestMapping("/test") 33 | public List test(HttpServletRequest request, HttpServletResponse response) { 34 | List accountList = this.testService.findAccountsById(3); 35 | logger.info(accountList); 36 | return accountList; 37 | } 38 | @ResponseBody 39 | @RequestMapping("/testXml") 40 | public List testXml(HttpServletRequest request, HttpServletResponse response) { 41 | List accountList = this.testXmlService.findAccountsById(3); 42 | logger.info(accountList); 43 | return accountList; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /spring-boot-with-mybatis/src/main/java/cn/kiiwii/framework/mybatis/druid/DruidConfiguration.java: -------------------------------------------------------------------------------- 1 | package cn.kiiwii.framework.mybatis.druid; 2 | 3 | import com.alibaba.druid.pool.DruidDataSource; 4 | import com.alibaba.druid.support.http.StatViewServlet; 5 | import com.alibaba.druid.support.http.WebStatFilter; 6 | import org.springframework.beans.factory.annotation.Value; 7 | import org.springframework.boot.web.servlet.FilterRegistrationBean; 8 | import org.springframework.boot.web.servlet.ServletRegistrationBean; 9 | import org.springframework.context.annotation.Bean; 10 | import org.springframework.context.annotation.Configuration; 11 | 12 | import javax.sql.DataSource; 13 | import java.sql.SQLException; 14 | 15 | /** 16 | * Created by zhong on 2016/9/5. 17 | */ 18 | @Configuration 19 | public class DruidConfiguration { 20 | @Value("${spring.datasource.driverClassName}") 21 | private String driver; 22 | @Value("${spring.datasource.url}") 23 | String url; 24 | @Value("${spring.datasource.username}") 25 | String username; 26 | @Value("${spring.datasource.password}") 27 | String password; 28 | @Value("${spring.datasource.initialSize}") 29 | int initialSize; 30 | @Value("${spring.datasource.minIdle}") 31 | int minIdle; 32 | @Value("${spring.datasource.maxActive}") 33 | int maxActive; 34 | @Value("${spring.datasource.maxWait}") 35 | long maxWait; 36 | @Value("${spring.datasource.timeBetweenEvictionRunsMillis}") 37 | long timeBetweenEvictionRunsMillis; 38 | @Value("${spring.datasource.minEvictableIdleTimeMillis}") 39 | long minEvictableIdleTimeMillis; 40 | @Value("${spring.datasource.validationQuery}") 41 | String validationQuery; 42 | @Value("${spring.datasource.testWhileIdle}") 43 | boolean testWhileIdle; 44 | @Value("${spring.datasource.testOnBorrow}") 45 | boolean testOnBorrow; 46 | @Value("${spring.datasource.testOnReturn}") 47 | boolean testOnReturn; 48 | @Value("${spring.datasource.poolPreparedStatements}") 49 | boolean poolPreparedStatements; 50 | @Value("${spring.datasource.maxPoolPreparedStatementPerConnectionSize}") 51 | int maxPoolPreparedStatementPerConnectionSize; 52 | @Value("${spring.datasource.filters}") 53 | String filters; 54 | @Value("${spring.datasource.connectionProperties}") 55 | String connectionProperties; 56 | 57 | @Bean 58 | public DataSource druidDataSource() { 59 | DruidDataSource druidDataSource = new DruidDataSource(); 60 | druidDataSource.setDriverClassName(driver); 61 | druidDataSource.setUrl(url); 62 | druidDataSource.setUsername(username); 63 | druidDataSource.setPassword(password); 64 | druidDataSource.setInitialSize(initialSize); 65 | druidDataSource.setMinIdle(minIdle); 66 | druidDataSource.setMaxActive(maxActive); 67 | druidDataSource.setMaxWait(maxWait); 68 | druidDataSource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis); 69 | druidDataSource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis); 70 | druidDataSource.setValidationQuery(validationQuery); 71 | druidDataSource.setTestWhileIdle(testWhileIdle); 72 | druidDataSource.setTestOnBorrow(testOnBorrow); 73 | druidDataSource.setTestOnReturn(testOnReturn); 74 | druidDataSource.setPoolPreparedStatements(poolPreparedStatements); 75 | druidDataSource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize); 76 | druidDataSource.setConnectionProperties(connectionProperties); 77 | try { 78 | druidDataSource.setFilters(filters); 79 | druidDataSource.init(); 80 | } catch (SQLException e) { 81 | e.printStackTrace(); 82 | } 83 | 84 | return druidDataSource; 85 | } 86 | 87 | @Bean 88 | public ServletRegistrationBean druidServlet() { 89 | 90 | ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*"); 91 | 92 | //添加初始化参数:initParams 93 | 94 | //白名单: 95 | //servletRegistrationBean.addInitParameter("allow","127.0.0.1"); 96 | //IP黑名单 (存在共同时,deny优先于allow) : 如果满足deny的话提示:Sorry, you are not permitted to view this page. 97 | //servletRegistrationBean.addInitParameter("deny","192.168.1.73"); 98 | //登录查看信息的账号密码. 99 | servletRegistrationBean.addInitParameter("loginUsername", "admin"); 100 | servletRegistrationBean.addInitParameter("loginPassword", "admin"); 101 | //是否能够重置数据. 102 | servletRegistrationBean.addInitParameter("resetEnable", "true"); 103 | return servletRegistrationBean; 104 | 105 | } 106 | 107 | @Bean 108 | public FilterRegistrationBean filterRegistrationBean() { 109 | FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(); 110 | filterRegistrationBean.setFilter(new WebStatFilter()); 111 | filterRegistrationBean.addUrlPatterns("/*"); 112 | filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*"); 113 | return filterRegistrationBean; 114 | } 115 | } 116 | -------------------------------------------------------------------------------- /spring-boot-with-mybatis/src/main/java/cn/kiiwii/framework/mybatis/mapper/TestMapper.java: -------------------------------------------------------------------------------- 1 | package cn.kiiwii.framework.mybatis.mapper; 2 | 3 | import cn.kiiwii.framework.mybatis.model.Account; 4 | import org.apache.ibatis.annotations.Insert; 5 | import org.apache.ibatis.annotations.Select; 6 | import org.apache.ibatis.annotations.Update; 7 | import org.springframework.cache.annotation.CacheEvict; 8 | import org.springframework.cache.annotation.Cacheable; 9 | 10 | import java.util.List; 11 | 12 | /** 13 | * Created by zhong on 2016/12/22. 14 | */ 15 | public interface TestMapper { 16 | 17 | String ADD_MONEY = "update account set money = money+#{1} where id = #{0}"; 18 | 19 | String MINUS_MONEY = "update account set money = money-#{1} where id = #{0}"; 20 | 21 | String INSERT_ACCOUT = "insert into account (name,money) values (#{name},#{money})"; 22 | 23 | String FIND_ACCOUNT_BY_ID = "select " + 24 | " id as id," + 25 | " name as name," + 26 | " money as money" + 27 | " from account " + 28 | " where " + 29 | " id = #{id}"; 30 | 31 | String FIND_ACCOUNTS_BY_ID = "select " + 32 | " id as id," + 33 | " name as name," + 34 | " money as money" + 35 | " from account " + 36 | " where " + 37 | " id >= #{id}"; 38 | 39 | @Update(ADD_MONEY) 40 | public int addMoney(int userId,float money); 41 | 42 | @Update(MINUS_MONEY) 43 | public int minusMoney(int userId,float money); 44 | 45 | @Insert(INSERT_ACCOUT) 46 | //@CacheEvict(value = {"indexCache"},allEntries = true,beforeInvocation = true) 47 | public int insertAccount(Account account); 48 | 49 | @Select(FIND_ACCOUNT_BY_ID) 50 | //@Cacheable(value = "indexCache",key = "'getAccountById'+#id") 51 | public Account getAccountById(int id); 52 | 53 | @Select(FIND_ACCOUNTS_BY_ID) 54 | //@Cacheable(value = "indexCache",key = "'findAccountsById'+#id") 55 | public List findAccountsById(int id); 56 | 57 | 58 | } 59 | -------------------------------------------------------------------------------- /spring-boot-with-mybatis/src/main/java/cn/kiiwii/framework/mybatis/mapper/TestXmlMapper.java: -------------------------------------------------------------------------------- 1 | package cn.kiiwii.framework.mybatis.mapper; 2 | 3 | import cn.kiiwii.framework.mybatis.model.Account; 4 | import org.apache.ibatis.annotations.Insert; 5 | import org.apache.ibatis.annotations.Select; 6 | import org.apache.ibatis.annotations.Update; 7 | import org.springframework.cache.annotation.CacheEvict; 8 | import org.springframework.cache.annotation.Cacheable; 9 | 10 | import java.util.List; 11 | 12 | /** 13 | * Created by zhong on 2016/12/22. 14 | */ 15 | public interface TestXmlMapper { 16 | 17 | public int addMoney(int userId, float money); 18 | 19 | public int minusMoney(int userId, float money); 20 | 21 | //@CacheEvict(value = {"indexCache"},allEntries = true,beforeInvocation = true) 22 | public int insertAccount(Account account); 23 | 24 | //@Cacheable(value = "indexCache",key = "'xmlgetAccountById'+#id") 25 | public Account getAccountById(int id); 26 | 27 | //@Cacheable(value = "indexCache",key = "'xmlfindAccountsById'+#id") 28 | public List findAccountsById(int id); 29 | } 30 | -------------------------------------------------------------------------------- /spring-boot-with-mybatis/src/main/java/cn/kiiwii/framework/mybatis/mapping/UserMapper.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 18 | 31 | 33 | insert into account (name,money) values (#{name},#{money}) 34 | 35 | -------------------------------------------------------------------------------- /spring-boot-with-mybatis/src/main/java/cn/kiiwii/framework/mybatis/model/Account.java: -------------------------------------------------------------------------------- 1 | package cn.kiiwii.framework.mybatis.model; 2 | 3 | import java.io.Serializable; 4 | 5 | public class Account implements Serializable{ 6 | 7 | private int id; 8 | private String name; 9 | private double money; 10 | 11 | public Account() { 12 | super(); 13 | } 14 | public int getId() { 15 | return id; 16 | } 17 | public void setId(int id) { 18 | this.id = id; 19 | } 20 | public String getName() { 21 | return name; 22 | } 23 | public void setName(String name) { 24 | this.name = name; 25 | } 26 | public double getMoney() { 27 | return money; 28 | } 29 | public void setMoney(double money) { 30 | this.money = money; 31 | } 32 | @Override 33 | public String toString() { 34 | return "Account [id=" + id + ", name=" + name + ", money=" + money 35 | + "]"; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /spring-boot-with-mybatis/src/main/java/cn/kiiwii/framework/mybatis/service/ITestService.java: -------------------------------------------------------------------------------- 1 | package cn.kiiwii.framework.mybatis.service; 2 | 3 | import cn.kiiwii.framework.mybatis.model.Account; 4 | 5 | import java.util.List; 6 | 7 | /** 8 | * Created by zhong on 2016/9/5. 9 | */ 10 | public interface ITestService { 11 | 12 | public void test(); 13 | 14 | public boolean transfer(float money, int from, int to) throws Exception; 15 | 16 | public int insertAccount(Account account) throws Exception; 17 | 18 | public Account findAccountById(int i); 19 | 20 | public List findAccountsById(int i); 21 | } 22 | -------------------------------------------------------------------------------- /spring-boot-with-mybatis/src/main/java/cn/kiiwii/framework/mybatis/service/ITestXmlService.java: -------------------------------------------------------------------------------- 1 | package cn.kiiwii.framework.mybatis.service; 2 | 3 | import cn.kiiwii.framework.mybatis.model.Account; 4 | 5 | import java.util.List; 6 | 7 | public interface ITestXmlService { 8 | 9 | 10 | public int insertAccount(Account account) throws Exception; 11 | 12 | public Account findAccountById(int i); 13 | 14 | public List findAccountsById(int i); 15 | } 16 | -------------------------------------------------------------------------------- /spring-boot-with-mybatis/src/main/java/cn/kiiwii/framework/mybatis/service/impl/TestServiceImpl.java: -------------------------------------------------------------------------------- 1 | package cn.kiiwii.framework.mybatis.service.impl; 2 | 3 | 4 | import cn.kiiwii.framework.mybatis.mapper.TestMapper; 5 | import cn.kiiwii.framework.mybatis.model.Account; 6 | import cn.kiiwii.framework.mybatis.service.ITestService; 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 | import org.springframework.transaction.annotation.Propagation; 12 | import org.springframework.transaction.annotation.Transactional; 13 | 14 | import javax.annotation.Resource; 15 | import java.util.List; 16 | 17 | /** 18 | * Created by zhong on 2016/9/5. 19 | */ 20 | @Service("testService") 21 | public class TestServiceImpl implements ITestService { 22 | 23 | Logger logger = LoggerFactory.getLogger(TestServiceImpl.class); 24 | 25 | @Resource 26 | private TestMapper testMapper; 27 | public void test() { 28 | } 29 | 30 | @Transactional(propagation= Propagation.REQUIRED ) 31 | @Override 32 | public boolean transfer(float money, int from, int to) throws Exception { 33 | 34 | this.testMapper.minusMoney(from, money); 35 | int i = 1/0; 36 | this.testMapper.addMoney(to, money); 37 | return true; 38 | } 39 | 40 | @Override 41 | public int insertAccount(Account account){ 42 | return this.testMapper.insertAccount(account); 43 | } 44 | 45 | @Override 46 | public Account findAccountById(int i) { 47 | 48 | return this.testMapper.getAccountById(i); 49 | } 50 | 51 | @Override 52 | 53 | public List findAccountsById(int i) { 54 | List accounts = this.testMapper.findAccountsById(i); 55 | return this.testMapper.findAccountsById(i); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /spring-boot-with-mybatis/src/main/java/cn/kiiwii/framework/mybatis/service/impl/TestXmlServiceImpl.java: -------------------------------------------------------------------------------- 1 | package cn.kiiwii.framework.mybatis.service.impl; 2 | 3 | import cn.kiiwii.framework.mybatis.mapper.TestXmlMapper; 4 | import cn.kiiwii.framework.mybatis.model.Account; 5 | import cn.kiiwii.framework.mybatis.service.ITestXmlService; 6 | import org.slf4j.Logger; 7 | import org.slf4j.LoggerFactory; 8 | import org.springframework.stereotype.Service; 9 | import org.springframework.transaction.annotation.Propagation; 10 | import org.springframework.transaction.annotation.Transactional; 11 | 12 | import javax.annotation.Resource; 13 | import java.util.List; 14 | 15 | @Service("testXmlService") 16 | public class TestXmlServiceImpl implements ITestXmlService { 17 | 18 | Logger logger = LoggerFactory.getLogger(TestXmlServiceImpl.class); 19 | 20 | @Resource 21 | private TestXmlMapper testXmlDAO; 22 | public void test() { 23 | } 24 | 25 | @Transactional(propagation= Propagation.REQUIRED ) 26 | @Override 27 | public int insertAccount(Account account){ 28 | return this.testXmlDAO.insertAccount(account); 29 | } 30 | 31 | @Override 32 | public Account findAccountById(int i) { 33 | 34 | return this.testXmlDAO.getAccountById(i); 35 | } 36 | 37 | @Override 38 | public List findAccountsById(int i) { 39 | List accounts = this.testXmlDAO.findAccountsById(i); 40 | return accounts; 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /spring-boot-with-mybatis/src/main/resources/application.properties: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhonglinlin1305/spring-boot-sample/efd45c9948a0e4e8379698dbb421852d291f4c45/spring-boot-with-mybatis/src/main/resources/application.properties -------------------------------------------------------------------------------- /spring-boot-with-mybatis/src/main/resources/log4j.properties: -------------------------------------------------------------------------------- 1 | log4j.rootLogger=INFO,CONSOLE,ROLLING_FILE 2 | 3 | ################## 4 | #Console Appender 5 | ################## 6 | log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender 7 | log4j.appender.Threshold=INFO 8 | log4j.appender.CONSOLE.Target=System.out 9 | log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout 10 | log4j.appender.CONSOLE.layout.ConversionPattern= [%p] %d %c - %m%n 11 | 12 | ######################## 13 | # Rolling File 14 | ######################## 15 | log4j.appender.ROLLING_FILE=org.apache.log4j.DailyRollingFileAppender 16 | log4j.appender.ROLLING_FILE.Threshold=INFO 17 | log4j.appender.ROLLING_FILE.File=../logs/mybatis/consol.log 18 | log4j.appender.ROLLING_FILE.Append=true 19 | log4j.appender.ROLLING_FILE.layout=org.apache.log4j.PatternLayout 20 | log4j.appender.ROLLING_FILE.layout.ConversionPattern=%d{yyyy-M-d HH:mm:ss}%x[%5p](%F:%L) %m%n -------------------------------------------------------------------------------- /spring-boot-with-mybatis/src/main/script/test.sql: -------------------------------------------------------------------------------- 1 | SELECT * FROM spring.test;CREATE TABLE `test` ( 2 | `id` int(11) NOT NULL AUTO_INCREMENT, 3 | `test_name` varchar(45) DEFAULT NULL, 4 | `test_num` int(11) DEFAULT '0', 5 | `test_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP, 6 | PRIMARY KEY (`id`) 7 | ) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8; -------------------------------------------------------------------------------- /spring-boot-with-mybatis/src/test/java/cn/kiiwii/framework/mybatis/TestServiceTest.java: -------------------------------------------------------------------------------- 1 | package cn.kiiwii.framework.mybatis; 2 | 3 | import cn.kiiwii.framework.mybatis.model.Account; 4 | import cn.kiiwii.framework.mybatis.service.ITestService; 5 | import cn.kiiwii.framework.mybatis.service.ITestXmlService; 6 | import org.junit.Test; 7 | import org.junit.runner.RunWith; 8 | import org.springframework.boot.test.SpringApplicationConfiguration; 9 | import org.springframework.test.context.ContextConfiguration; 10 | import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 11 | import org.springframework.test.context.web.WebAppConfiguration; 12 | 13 | import javax.annotation.Resource; 14 | import java.util.List; 15 | 16 | /** 17 | * Created by zhong on 2016/12/22. 18 | */ 19 | @RunWith(SpringJUnit4ClassRunner.class) 20 | @SpringApplicationConfiguration(classes = Application.class) 21 | @WebAppConfiguration 22 | public class TestServiceTest { 23 | 24 | @Resource(name = "testService") 25 | private ITestService testService; 26 | @Resource(name = "testXmlService") 27 | private ITestXmlService testXmlService; 28 | 29 | @Test 30 | public void testInsert(){ 31 | 32 | Account account = new Account(); 33 | account.setMoney(1000); 34 | account.setName("kael"); 35 | try { 36 | int id = testService.insertAccount(account); 37 | System.out.println("==============================="+id); 38 | } catch (Exception e) { 39 | // TODO Auto-generated catch block 40 | e.printStackTrace(); 41 | } 42 | } 43 | @Test 44 | public void testXmlInsert(){ 45 | 46 | Account account = new Account(); 47 | account.setMoney(1000); 48 | account.setName("小小1"); 49 | try { 50 | int id = testXmlService.insertAccount(account); 51 | System.out.println("==============================="+id); 52 | } catch (Exception e) { 53 | // TODO Auto-generated catch block 54 | e.printStackTrace(); 55 | } 56 | } 57 | 58 | @Test 59 | public void testTransfer() { 60 | boolean b; 61 | try { 62 | b = testService.transfer(200, 1, 2); 63 | if(b){ 64 | System.out.println("转账成功"); 65 | }else{ 66 | System.out.println("转账失败"); 67 | } 68 | } catch (Exception e) { 69 | e.printStackTrace(); 70 | System.out.println("转账失败"); 71 | } 72 | 73 | } 74 | 75 | @Test 76 | public void testFind(){ 77 | 78 | try { 79 | Account account = testService.findAccountById(3); 80 | System.out.println(account); 81 | } catch (Exception e) { 82 | // TODO Auto-generated catch block 83 | e.printStackTrace(); 84 | } 85 | } 86 | 87 | @Test 88 | public void testList(){ 89 | 90 | try { 91 | List accounts = testService.findAccountsById(3); 92 | System.out.println(accounts); 93 | } catch (Exception e) { 94 | e.printStackTrace(); 95 | } 96 | } 97 | @Test 98 | public void testXmlList(){ 99 | 100 | try { 101 | // List accounts = testXmlService.findAccountsById(3); 102 | Account account = testXmlService.findAccountById(3); 103 | Account account2 = testXmlService.findAccountById(3); 104 | System.out.println(account); 105 | } catch (Exception e) { 106 | e.printStackTrace(); 107 | } 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /spring-boot-with-schedule/pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4 | spring-boot-sample 5 | cn.kiiwii.framework 6 | 1.0-SNAPSHOT 7 | 8 | 4.0.0 9 | 10 | spring-boot-with-schedule 11 | jar 12 | 13 | spring-boot-with-schedule 14 | http://maven.apache.org 15 | 16 | 17 | UTF-8 18 | 19 | 20 | 21 | 22 | junit 23 | junit 24 | 4.12 25 | test 26 | 27 | 28 | org.springframework.boot 29 | spring-boot-starter-web 30 | 31 | 32 | org.springframework.boot 33 | spring-boot-starter 34 | 35 | 36 | org.springframework.boot 37 | spring-boot-starter-logging 38 | 39 | 40 | 41 | 42 | org.springframework.boot 43 | spring-boot-starter-jdbc 44 | 45 | 46 | org.springframework.boot 47 | spring-boot-starter-jdbc 48 | 49 | 50 | org.springframework.boot 51 | spring-boot-starter-log4j 52 | 1.3.7.RELEASE 53 | 54 | 55 | mysql 56 | mysql-connector-java 57 | 5.1.38 58 | 59 | 60 | com.alibaba 61 | druid 62 | 1.0.25 63 | 64 | 65 | org.springframework 66 | spring-context 67 | 4.3.2.RELEASE 68 | 69 | 70 | 71 | 72 | 73 | 74 | org.apache.maven.plugins 75 | maven-compiler-plugin 76 | 3.2 77 | 78 | 1.7 79 | 1.7 80 | 81 | 82 | 83 | org.springframework.boot 84 | spring-boot-maven-plugin 85 | 86 | 87 | 88 | repackage 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | -------------------------------------------------------------------------------- /spring-boot-with-schedule/src/main/java/cn/kiiwii/framework/Application.java: -------------------------------------------------------------------------------- 1 | package cn.kiiwii.framework; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | import org.springframework.boot.SpringApplication; 6 | import org.springframework.boot.autoconfigure.EnableAutoConfiguration; 7 | import org.springframework.boot.autoconfigure.ImportAutoConfiguration; 8 | import org.springframework.boot.autoconfigure.SpringBootApplication; 9 | import org.springframework.web.bind.annotation.RestController; 10 | 11 | /** 12 | * Created by zhong on 2016/11/10. 13 | */ 14 | @RestController 15 | @SpringBootApplication 16 | @EnableAutoConfiguration 17 | @ImportAutoConfiguration 18 | public class Application { 19 | 20 | static Logger logger = LoggerFactory.getLogger(Application.class); 21 | 22 | 23 | public static void main(String[] args) throws Exception { 24 | SpringApplication.run(Application.class, args); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /spring-boot-with-schedule/src/main/java/cn/kiiwii/framework/controller/TestController.java: -------------------------------------------------------------------------------- 1 | package cn.kiiwii.framework.controller; 2 | 3 | import cn.kiiwii.framework.service.ITestService; 4 | import org.slf4j.Logger; 5 | import org.slf4j.LoggerFactory; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.stereotype.Controller; 8 | import org.springframework.web.bind.annotation.RequestMapping; 9 | import org.springframework.web.bind.annotation.RestController; 10 | 11 | /** 12 | * Created by zhong on 2016/11/10. 13 | */ 14 | @RestController 15 | @Controller 16 | public class TestController { 17 | @Autowired 18 | private ITestService testService; 19 | private Logger logger = LoggerFactory.getLogger(this.getClass()); 20 | 21 | @RequestMapping("/test") 22 | public String greeting() { 23 | testService.test(); 24 | return "hello"; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /spring-boot-with-schedule/src/main/java/cn/kiiwii/framework/dao/ITestDAO.java: -------------------------------------------------------------------------------- 1 | package cn.kiiwii.framework.dao; 2 | 3 | /** 4 | * Created by zhong on 2016/9/5. 5 | */ 6 | public interface ITestDAO { 7 | void test(); 8 | } 9 | -------------------------------------------------------------------------------- /spring-boot-with-schedule/src/main/java/cn/kiiwii/framework/dao/impl/TestDAOImpl.java: -------------------------------------------------------------------------------- 1 | package cn.kiiwii.framework.dao.impl; 2 | 3 | import cn.kiiwii.framework.dao.ITestDAO; 4 | import org.springframework.beans.factory.annotation.Autowired; 5 | import org.springframework.jdbc.core.JdbcTemplate; 6 | import org.springframework.stereotype.Repository; 7 | 8 | import java.util.List; 9 | import java.util.Map; 10 | 11 | /** 12 | * Created by zhong on 2016/9/5. 13 | */ 14 | @Repository("testDAO") 15 | public class TestDAOImpl implements ITestDAO { 16 | 17 | @Autowired 18 | private JdbcTemplate jdbcTemplate; 19 | @Override 20 | public void test() { 21 | List> list = this.jdbcTemplate.queryForList("select * from test"); 22 | System.out.println(list); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /spring-boot-with-schedule/src/main/java/cn/kiiwii/framework/druid/DruidConfiguration.java: -------------------------------------------------------------------------------- 1 | package cn.kiiwii.framework.druid; 2 | 3 | import com.alibaba.druid.pool.DruidDataSource; 4 | import com.alibaba.druid.support.http.StatViewServlet; 5 | import com.alibaba.druid.support.http.WebStatFilter; 6 | import org.springframework.beans.factory.annotation.Value; 7 | import org.springframework.boot.web.servlet.FilterRegistrationBean; 8 | import org.springframework.boot.web.servlet.ServletRegistrationBean; 9 | import org.springframework.context.annotation.Bean; 10 | import org.springframework.context.annotation.Configuration; 11 | 12 | import javax.sql.DataSource; 13 | import java.sql.SQLException; 14 | 15 | /** 16 | * Created by zhong on 2016/9/5. 17 | */ 18 | @Configuration 19 | public class DruidConfiguration { 20 | @Value("${spring.datasource.driverClassName}") 21 | private String driver; 22 | @Value("${spring.datasource.url}") 23 | String url; 24 | @Value("${spring.datasource.username}") 25 | String username; 26 | @Value("${spring.datasource.password}") 27 | String password; 28 | @Value("${spring.datasource.initialSize}") 29 | int initialSize; 30 | @Value("${spring.datasource.minIdle}") 31 | int minIdle; 32 | @Value("${spring.datasource.maxActive}") 33 | int maxActive; 34 | @Value("${spring.datasource.maxWait}") 35 | long maxWait; 36 | @Value("${spring.datasource.timeBetweenEvictionRunsMillis}") 37 | long timeBetweenEvictionRunsMillis; 38 | @Value("${spring.datasource.minEvictableIdleTimeMillis}") 39 | long minEvictableIdleTimeMillis; 40 | @Value("${spring.datasource.validationQuery}") 41 | String validationQuery; 42 | @Value("${spring.datasource.testWhileIdle}") 43 | boolean testWhileIdle; 44 | @Value("${spring.datasource.testOnBorrow}") 45 | boolean testOnBorrow; 46 | @Value("${spring.datasource.testOnReturn}") 47 | boolean testOnReturn; 48 | @Value("${spring.datasource.poolPreparedStatements}") 49 | boolean poolPreparedStatements; 50 | @Value("${spring.datasource.maxPoolPreparedStatementPerConnectionSize}") 51 | int maxPoolPreparedStatementPerConnectionSize; 52 | @Value("${spring.datasource.filters}") 53 | String filters; 54 | @Value("${spring.datasource.connectionProperties}") 55 | String connectionProperties; 56 | 57 | @Bean 58 | public ServletRegistrationBean druidServlet() { 59 | 60 | ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(),"/druid/*"); 61 | 62 | //添加初始化参数:initParams 63 | 64 | //白名单: 65 | //servletRegistrationBean.addInitParameter("allow","127.0.0.1"); 66 | //IP黑名单 (存在共同时,deny优先于allow) : 如果满足deny的话提示:Sorry, you are not permitted to view this page. 67 | //servletRegistrationBean.addInitParameter("deny","192.168.1.73"); 68 | //登录查看信息的账号密码. 69 | servletRegistrationBean.addInitParameter("loginUsername","admin"); 70 | servletRegistrationBean.addInitParameter("loginPassword","admin"); 71 | //是否能够重置数据. 72 | servletRegistrationBean.addInitParameter("resetEnable","true"); 73 | return servletRegistrationBean; 74 | 75 | } 76 | 77 | @Bean 78 | public DataSource druidDataSource() { 79 | DruidDataSource druidDataSource = new DruidDataSource(); 80 | druidDataSource.setDriverClassName(driver); 81 | druidDataSource.setUrl(url); 82 | druidDataSource.setUsername(username); 83 | druidDataSource.setPassword(password); 84 | druidDataSource.setInitialSize(initialSize); 85 | druidDataSource.setMinIdle(minIdle); 86 | druidDataSource.setMaxActive(maxActive); 87 | druidDataSource.setMaxWait(maxWait); 88 | druidDataSource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis); 89 | druidDataSource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis); 90 | druidDataSource.setValidationQuery(validationQuery); 91 | druidDataSource.setTestWhileIdle(testWhileIdle); 92 | druidDataSource.setTestOnBorrow(testOnBorrow); 93 | druidDataSource.setTestOnReturn(testOnReturn); 94 | druidDataSource.setPoolPreparedStatements(poolPreparedStatements); 95 | druidDataSource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize); 96 | druidDataSource.setConnectionProperties(connectionProperties); 97 | try { 98 | druidDataSource.setFilters(filters); 99 | druidDataSource.init(); 100 | } catch (SQLException e) { 101 | e.printStackTrace(); 102 | } 103 | return druidDataSource; 104 | } 105 | @Bean 106 | public FilterRegistrationBean filterRegistrationBean() { 107 | FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(); 108 | filterRegistrationBean.setFilter(new WebStatFilter()); 109 | filterRegistrationBean.addUrlPatterns("/*"); 110 | filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*"); 111 | return filterRegistrationBean; 112 | } 113 | } 114 | -------------------------------------------------------------------------------- /spring-boot-with-schedule/src/main/java/cn/kiiwii/framework/schedule/Scheduling.java: -------------------------------------------------------------------------------- 1 | package cn.kiiwii.framework.schedule; 2 | 3 | import cn.kiiwii.framework.service.ITestService; 4 | import org.slf4j.Logger; 5 | import org.slf4j.LoggerFactory; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.context.annotation.Configuration; 8 | import org.springframework.scheduling.annotation.EnableScheduling; 9 | import org.springframework.scheduling.annotation.Scheduled; 10 | 11 | /** 12 | * Created by zhong on 2016/11/10. 13 | */ 14 | @Configuration 15 | @EnableScheduling 16 | public class Scheduling { 17 | private final Logger logger = LoggerFactory.getLogger(this.getClass()); 18 | @Autowired 19 | private ITestService testService; 20 | 21 | /** 22 | * 一个cron表达式有至少6个(也可能7个)有空格分隔的时间元素。按顺序依次为 23 | * 秒(0~59) 24 | * 分钟(0~59) 25 | * 小时(0~23) 26 | * 天(月)(0~31,但是你需要考虑你月的天数) 27 | * 月(0~11) 28 | * 天(星期)(1~7 1=SUN 或 SUN,MON,TUE,WED,THU,FRI,SAT) 29 | * 年份(1970-2099) 30 | * 31 | * 其中每个元素可以是一个值(如6),一个连续区间(9-12),一个间隔时间(8-18/4)(/表示每隔4小时),一个列表(1,3,5),通配符。由于"月份中的日期"和"星期中的日期"这两个元素互斥的,必须要对其中一个设置? 32 | 33 | * 0 0 10,14,16 * * ? 每天上午10点,下午2点,4点 34 | * 0 0/30 9-17 * * ? 朝九晚五工作时间内每半小时 35 | * 0 0 12 ? * WED 表示每个星期三中午12点 36 | * "0 0 12 * * ?" 每天中午12点触发 37 | * "0 15 10 ? * *" 每天上午10:15触发 38 | * "0 15 10 * * ?" 每天上午10:15触发 39 | * "0 15 10 * * ? *" 每天上午10:15触发 40 | * "0 15 10 * * ? 2005" 2005年的每天上午10:15触发 41 | * "0 * 14 * * ?" 在每天下午2点到下午2:59期间的每1分钟触发 42 | * "0 0/5 14 * * ?" 在每天下午2点到下午2:55期间的每5分钟触发 43 | * "0 0/5 14,18 * * ?" 在每天下午2点到2:55期间和下午6点到6:55期间的每5分钟触发 44 | * "0 0-5 14 * * ?" 在每天下午2点到下午2:05期间的每1分钟触发 45 | * "0 10,44 14 ? 3 WED" 每年三月的星期三的下午2:10和2:44触发 46 | * "0 15 10 ? * MON-FRI" 周一至周五的上午10:15触发 47 | * "0 15 10 15 * ?" 每月15日上午10:15触发 48 | * "0 15 10 L * ?" 每月最后一日的上午10:15触发 49 | * "0 15 10 ? * 6L" 每月的最后一个星期五上午10:15触发 50 | * "0 15 10 ? * 6L 2002-2005" 2002年至2005年的每月的最后一个星期五上午10:15触发 51 | * "0 15 10 ? * 6#3" 每月的第三个星期五上午10:15触发 52 | */ 53 | @Scheduled(cron = "0/20 * * * * ?") // 每20秒执行一次 54 | public void scheduler() { 55 | testService.test(); 56 | logger.info("excute Schedule"); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /spring-boot-with-schedule/src/main/java/cn/kiiwii/framework/service/ITestService.java: -------------------------------------------------------------------------------- 1 | package cn.kiiwii.framework.service; 2 | 3 | /** 4 | * Created by zhong on 2016/9/5. 5 | */ 6 | public interface ITestService { 7 | 8 | void test(); 9 | } 10 | -------------------------------------------------------------------------------- /spring-boot-with-schedule/src/main/java/cn/kiiwii/framework/service/impl/TestServiceImpl.java: -------------------------------------------------------------------------------- 1 | package cn.kiiwii.framework.service.impl; 2 | 3 | import cn.kiiwii.framework.dao.ITestDAO; 4 | import cn.kiiwii.framework.service.ITestService; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.stereotype.Service; 7 | 8 | /** 9 | * Created by zhong on 2016/9/5. 10 | */ 11 | @Service("testService") 12 | public class TestServiceImpl implements ITestService { 13 | 14 | @Autowired 15 | ITestDAO testDAO; 16 | 17 | @Override 18 | public void test() { 19 | this.testDAO.test(); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /spring-boot-with-schedule/src/main/resources/application.properties: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhonglinlin1305/spring-boot-sample/efd45c9948a0e4e8379698dbb421852d291f4c45/spring-boot-with-schedule/src/main/resources/application.properties -------------------------------------------------------------------------------- /spring-boot-with-schedule/src/main/resources/log4j.properties: -------------------------------------------------------------------------------- 1 | log4j.rootLogger=INFO,CONSOLE,ROLLING_FILE 2 | 3 | ################## 4 | #Console Appender 5 | ################## 6 | log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender 7 | log4j.appender.Threshold=INFO 8 | log4j.appender.CONSOLE.Target=System.out 9 | log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout 10 | log4j.appender.CONSOLE.layout.ConversionPattern= [%p] %d %c - %m%n 11 | 12 | ######################## 13 | # Rolling File 14 | ######################## 15 | log4j.appender.ROLLING_FILE=org.apache.log4j.DailyRollingFileAppender 16 | log4j.appender.ROLLING_FILE.Threshold=INFO 17 | log4j.appender.ROLLING_FILE.File=../logs/schedule/consol.log 18 | log4j.appender.ROLLING_FILE.Append=true 19 | log4j.appender.ROLLING_FILE.layout=org.apache.log4j.PatternLayout 20 | log4j.appender.ROLLING_FILE.layout.ConversionPattern=%d{yyyy-M-d HH:mm:ss}%x[%5p](%F:%L) %m%n -------------------------------------------------------------------------------- /spring-boot-with-schedule/src/main/script/test.sql: -------------------------------------------------------------------------------- 1 | -- MySQL dump 10.13 Distrib 5.6.23, for Win64 (x86_64) 2 | -- 3 | -- Host: localhost Database: spring 4 | -- ------------------------------------------------------ 5 | -- Server version 5.7.9-log 6 | 7 | /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; 8 | /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; 9 | /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; 10 | /*!40101 SET NAMES utf8 */; 11 | /*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; 12 | /*!40103 SET TIME_ZONE='+00:00' */; 13 | /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; 14 | /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; 15 | /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; 16 | /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; 17 | 18 | -- 19 | -- Table structure for table `test` 20 | -- 21 | 22 | DROP TABLE IF EXISTS `test`; 23 | /*!40101 SET @saved_cs_client = @@character_set_client */; 24 | /*!40101 SET character_set_client = utf8 */; 25 | CREATE TABLE `test` ( 26 | `id` int(11) NOT NULL AUTO_INCREMENT, 27 | `test_name` varchar(45) DEFAULT NULL, 28 | `test_num` int(11) DEFAULT '0', 29 | `test_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP, 30 | PRIMARY KEY (`id`) 31 | ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8; 32 | /*!40101 SET character_set_client = @saved_cs_client */; 33 | 34 | -- 35 | -- Dumping data for table `test` 36 | -- 37 | 38 | LOCK TABLES `test` WRITE; 39 | /*!40000 ALTER TABLE `test` DISABLE KEYS */; 40 | INSERT INTO `test` VALUES (1,'xiao',2,'2016-11-10 09:41:02'),(2,'li',3,'2016-11-10 09:41:02'),(3,'xi',1,'2016-11-10 09:41:02'); 41 | /*!40000 ALTER TABLE `test` ENABLE KEYS */; 42 | UNLOCK TABLES; 43 | 44 | -- 45 | -- Dumping events for database 'spring' 46 | -- 47 | 48 | -- 49 | -- Dumping routines for database 'spring' 50 | -- 51 | /*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; 52 | 53 | /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; 54 | /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; 55 | /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; 56 | /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; 57 | /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; 58 | /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; 59 | /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; 60 | 61 | -- Dump completed on 2016-11-10 17:44:00 62 | -------------------------------------------------------------------------------- /spring-boot-with-schedule/src/test/java/cn/kiiwii/framework/AppTest.java: -------------------------------------------------------------------------------- 1 | package cn.kiiwii.framework; 2 | 3 | import junit.framework.Test; 4 | import junit.framework.TestCase; 5 | import junit.framework.TestSuite; 6 | 7 | /** 8 | * Unit test for simple App. 9 | */ 10 | public class AppTest 11 | extends TestCase 12 | { 13 | /** 14 | * Create the test case 15 | * 16 | * @param testName name of the test case 17 | */ 18 | public AppTest( String testName ) 19 | { 20 | super( testName ); 21 | } 22 | 23 | /** 24 | * @return the suite of tests being tested 25 | */ 26 | public static Test suite() 27 | { 28 | return new TestSuite( AppTest.class ); 29 | } 30 | 31 | /** 32 | * Rigourous Test :-) 33 | */ 34 | public void testApp() 35 | { 36 | assertTrue( true ); 37 | } 38 | } 39 | --------------------------------------------------------------------------------