深圳住房和城乡建设局网站首页,north WordPress教程,wordpress文章tags,建立网站的目的和功能概述
1.基于Spring框架的“约定优先于配置#xff08;COC#xff09;”理念以及最佳实践之路。 2.针对日常企业应用研发各种场景的Spring-boot-starter自动配置依赖模块#xff0c;且“开箱即用”#xff08;约定spring-boot-starter- 作为命名前缀#xff0c;都位于org.…概述
1.基于Spring框架的“约定优先于配置COC”理念以及最佳实践之路。 2.针对日常企业应用研发各种场景的Spring-boot-starter自动配置依赖模块且“开箱即用”约定spring-boot-starter- 作为命名前缀都位于org.springframenwork.boot包或者命名空间下。
spring-boot-starter-jdbc
默认情况下当我们没有配置任何DataSource,SpringBoot会为我们自动配置一个DataSource这种自动配置的方式一般适用于测试开发还是自己配置一个DataSource的实例比较好。 如果我们的工程只依赖一个数据库那么使用DataSource自动配置模块提供的参数是最方便的
spring.datasource.urljdbc:mysql://{datasource host}:3306/{databaseName}
spring.datasource.username{database username}
spring.datasource.passwd{database passwd}还会自动配置的有JdbcTemplate DateSourceTransactionManager等我们只要在使用的时候注入Autowired就好了 此外SpringBoot还支持的数据库有spring-boot-data-jpa spring-boot-data-mongodb
spring-boot-starter-web
在当下项目运行mvn spring-boot:run就可以直接启用一个嵌套了tomcat的web应用。 如果没有提供任何服务的Cotroller,访问任何路径都会返回一个springBoot默认的错误页面Whitelabel error page。 嵌入式Web容器层面的约定和定制
spring-boot-starter-web默认使用嵌套式的Tomcat作为Web容器对外提供HTTP服务默认端口8080对外监听和提供服务。 我们同样可以使用spring-boot-starter-jetty或者spring-boot-starter-undertow作为Web容器。 想改变默认的配置端口可以在application.properties中指定
server.port 9000(the port number you want)类似的配置还有
server.address
server.ssl.*
server.tomcat.*如果上诉仍然没有办法满足要求springBoot支持对嵌入式的Web容器实例进行定制可以通过向IoC容器中注册一个EmbeddedServletContainerCustomizer类型的组件来对嵌入式的Web容器进行定制
public class UnveilSpringEmbeddedTomcatCustomizer implements EmbeddedServletContainer{public void customize(ConfigurableEmbeddedServletContainer container){container.setPort(9999);container.setContextPath(C\\hello);...}}spring-boot-starter-test
进行springboot单元测试
RunWith(SpringRunner.class)
SpringBootTest
public class UserControllerTest {Autowiredprivate WebApplicationContext wac;private MockMvc mockMvc;Beforepublic void setup() {mockMvc MockMvcBuilders.webAppContextSetup(wac).build();}Testpublic void whenQuerySuccess() throws Exception {String result mockMvc.perform(get(/user).param(username, jojo).param(age, 18).param(ageTo, 60).param(xxx, yyy)// .param(size, 15) //MockMvcRequestBuilders// .param(page, 3)// .param(sort, age,desc).contentType(MediaType.APPLICATION_JSON_UTF8)).andExpect(status().isOk()).andExpect(jsonPath($.length()).value(3)) //MockMvcResultMatchers.andReturn().getResponse().getContentAsString();System.out.println(result);}spring-boot-devtools
当配置了 devtools 后我们在classpath修改任何文件项目都将会自动重启。 1某些资源在更改时不一定需要触发重新启动。例如, Thymeleaf 模板可以就地进行编辑。默认情况下更改资源路径包括了/META-INF/maven, /META-INF/resources ,/resources ,/static ,/public 或者 /templates 不会触发重新启动, 但会触发实时重新加载。
如果逆向排除这些路径可以使用如下配置
spring.devtools.restart.excludestatic/,public/
2如果要保留这些默认值并添加其他排除项, 请使用 spring.devtools.restart.additional-exclude 属性代替。
3通过 System.setProperty(“spring.devtools.restart.enabled”, “false”); 方法可以在SpringApplication.run()方法运行天使用关闭 devtools。
4当我们再次启动 App.java 的时候使用的加载器就变为了 restartedMain 了说明热部署已经成功。 注意点devtools 由于是双类加载机制再结合了通用Mapper后可能会出现 java.lang.ClassCastException 异常(例如说class x.x.A cannot be cast to x.x.A。)。
解决方案就如下
在 src/main/resources 中创建 META-INF 目录在此目录下添加 spring-devtools.properties 配置内容如下
restart.include.mapper/mapper-[\w-\.]jar restart.include.pagehelper/pagehelper-[\w-\.]jar
spring-boot-starter-aop
AOP:Aspect Oriented Programming,面向切面编程 spring-boot-starter-aop主要由2部分组成 1.位于spring-boot-autoconfigure的org.sringframework.boot.autoconfigure.aop.AopAutoConfiguration提供的Configuration配置类和相应的配置项即下面的2个配置项
spring.aop.autotrue
spring.aop.proxy-target-classfalse2.spring-boot-starter-aop模块提供了针对spring-aop aspectjrt 和aspectjweaver的依赖
spring-boot-starter-security
应用安全 spring-boot-starter-security 主要面向的是Web应用开发配合spring-boot-starter-web spring-boot-starter-security 默认会提供一个基于HTTP Basic认证的安全防护策略默认用户为user,访问密码则在当前web应用启动的时候打印到控制台要想定制则在配置文件如下进行配置
security.user.name{username}
security.user.password{passwd}除此之外spring-boot-starter-security还会默认启动一些必要的Web安全防护比如针对XSS CSRF等场针对Web应用的攻击同时也会将一些常见的静态资源路径排除在安全防护之外。 AuthenticationManager AccessDecisionManager AbstractSecurityInterceptor被称为Spring Security的基础铁三角前2者负责制定规则 AbstractSecurityInterceptor负责执行。我们常见的Filter类就可以定制和扩展SpringSecurity的防护机制。
进一步定制spring-boot-starter-security 上诉使用SecurityProperties暴露的配置项即以security.*对spring-boot-starter-security进行简单的配置还可以通过给出一个继承了WebSecurityConfigurerAdapter的JavaConfig配置类对spring-boot-starter-security的行为进行更深级别的定制例如
使用其他的AuthenticationManager实例对默认的HttpSecurity定义的资源访问的规则重新定义对默认提供的WebSecurity行为进行调整一般配OrderSecurityProperties.ACCESS_OVERRIDE_ORDER进行标注。
mybatis-spring-boot-starter
MyBatis-Spring-Boot-Starter依赖将会提供如下
自动检测现有的DataSource将创建并注册SqlSessionFactory的实例该实例使用SqlSessionFactoryBean将该DataSource作为输入进行传递将创建并注册从SqlSessionFactory中获取的SqlSessionTemplate的实例。自动扫描您的mappers将它们链接到SqlSessionTemplate并将其注册到Spring上下文以便将它们注入到您的bean中。
使用了该Starter之后只需要定义一个DataSource即可application.properties或application.yml中可配置它会自动创建使用该DataSource的SqlSessionFactoryBean以及SqlSessionTemplate。会自动扫描你的Mappers连接到SqlSessionTemplate并注册到Spring上下文中。
pagehelper-spring-boot-starter
引入的jar包必须是要pagehelper-spring-boot-starter如果单独引入pagehelper的话分页会不成功. 使用时PageHelper.startPage(pageNum, pageSize)一定要放在列表查询上面这样在查询时会查出相应的数据量且会查询出总数像图中总数量有两条page里面查询出来了是2但list只查出了1条因为我传的分页是pageNo1,pageSize1
PageHelper.startPage(pageNum, pageSize);
ListSystemUserPageVo systemUserList systemUserMapper.page(find);
PageInfoSystemUserPageVo page new PageInfo(systemUserList);打印的sql如下所示
Preparing: SELECT count(0) FROM (SELECT su.id, su.name, su.nick_name, su.email, su.phone, su.sex, su.fail_num, su.status, su.create_time, su.update_time, GROUP_CONCAT(sr.name) AS rolesName FROM SYSTEM_USER su, system_user_role sur, system_role sr WHERE su.id sur.user_id AND sur.role_id sr.id GROUP BY su.id) table_count
Parameters:
Total: 1
Preparing: SELECT su.id, su.name, su.nick_name, su.email, su.phone, su.sex, su.fail_num, su.status, su.create_time, su.update_time, group_concat(sr.name) as rolesName FROM SYSTEM_USER su, system_user_role sur, system_role sr WHERE su.id sur.user_id AND sur.role_id sr.id GROUP BY su.id LIMIT ?
Parameters: 1(Integer)
Total: 1druid-spring-boot-starter
Druid是Java语言中最好的数据库连接池。Druid能够提供强大的监控和扩展功能。DruidDataSource支持的数据库 理论上说支持所有有jdbc驱动的数据库。最近发现Druid在springboot框架下有更加好用的Druid Spring Boot Starter可以省去原本写Druid的一些配置文件或者Configuration来配置直接将配置写在application.yml里看起来更简单一些。 编写application.yml部分说明写在注释了 spring:application:name: springboot-test-exam1datasource:# 使用阿里的Druid连接池type: com.alibaba.druid.pool.DruidDataSourcedriver-class-name: com.mysql.jdbc.Driver# 填写你数据库的url、登录名、密码和数据库名url: jdbc:mysql://localhost:3306/databaseName?useSSLfalsecharacterEncodingutf8username: rootpassword: rootdruid:# 连接池的配置信息# 初始化大小最小最大initial-size: 5min-idle: 5maxActive: 20# 配置获取连接等待超时的时间maxWait: 60000# 配置间隔多久才进行一次检测检测需要关闭的空闲连接单位是毫秒timeBetweenEvictionRunsMillis: 60000# 配置一个连接在池中最小生存的时间单位是毫秒minEvictableIdleTimeMillis: 300000validationQuery: SELECT 1 FROM DUALtestWhileIdle: truetestOnBorrow: falsetestOnReturn: false# 打开PSCache并且指定每个连接上PSCache的大小poolPreparedStatements: truemaxPoolPreparedStatementPerConnectionSize: 20# 配置监控统计拦截的filters去掉后监控界面sql无法统计wall用于防火墙filters: stat,wall,log4j# 通过connectProperties属性来打开mergeSql功能慢SQL记录connectionProperties: druid.stat.mergeSql\true;druid.stat.slowSqlMillis\5000# 配置DruidStatFilterweb-stat-filter:enabled: trueurl-pattern: /*exclusions: *.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*# 配置DruidStatViewServletstat-view-servlet:url-pattern: /druid/*# IP白名单(没有配置或者为空则允许所有访问)allow: 127.0.0.1,192.168.163.1# IP黑名单 (存在共同时deny优先于allow)deny: 192.168.1.73# 禁用HTML页面上的“Reset All”功能reset-enable: false# 登录名login-username: admin# 登录密码login-password: 123456为了方便使用application.properties的读者使用下面的配置和上面相同
server.port8080spring.application.namespringboot-test-exam1spring.datasource.typecom.alibaba.druid.pool.DruidDataSource
spring.datasource.driver-class-namecom.mysql.jdbc.Driver
spring.datasource.urljdbc:mysql://localhost:3306/databaseName?useSSLfalsecharacterEncodingutf8
spring.datasource.usernameroot
spring.datasource.passwordroot
spring.datasource.druid.initial-size5
spring.datasource.druid.min-idle5
spring.datasource.druid.maxActive20
spring.datasource.druid.maxWait60000
spring.datasource.druid.timeBetweenEvictionRunsMillis60000
spring.datasource.druid.minEvictableIdleTimeMillis300000
spring.datasource.druid.validationQuerySELECT 1 FROM DUAL
spring.datasource.druid.testWhileIdletrue
spring.datasource.druid.testOnBorrowfalse
spring.datasource.druid.testOnReturnfalse
spring.datasource.druid.poolPreparedStatementstrue
spring.datasource.druid.maxPoolPreparedStatementPerConnectionSize20
spring.datasource.druid.filtersstat,wall,log4j
spring.datasource.druid.connectionPropertiesdruid.stat.mergeSql\true;druid.stat.slowSqlMillis\5000
spring.datasource.druid.web-stat-filter.enabledtrue
spring.datasource.druid.web-stat-filter.url-pattern/*
spring.datasource.druid.web-stat-filter.exclusions*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*
spring.datasource.druid.stat-view-servlet.url-pattern/druid/*
spring.datasource.druid.stat-view-servlet.allow127.0.0.1,192.168.163.1
spring.datasource.druid.stat-view-servlet.deny192.168.1.73
spring.datasource.druid.stat-view-servlet.reset-enablefalse
spring.datasource.druid.stat-view-servlet.login-usernameadmin
spring.datasource.druid.stat-view-servlet.login-password123456mybatis-generator-core
SSM框架可以使用mybatis-generator-core-1.3.2.jar来自动生成代码以下是配置和使用的代码。 generatorConfig.xml
?xml version1.0 encodingUTF-8?
!DOCTYPE generatorConfigurationPUBLIC -//mybatis.org//DTD MyBatis Generator Configuration 1.0//ENhttp://mybatis.org/dtd/mybatis-generator-config_1_0.dtdgeneratorConfigurationcontext idtestTables targetRuntimeMyBatis3commentGenerator!-- 是否去除自动生成的注释 true是 false:否 --property namesuppressAllComments valuetrue //commentGenerator!--数据库连接的信息驱动类、连接地址、用户名、密码 --jdbcConnection driverClasscom.mysql.jdbc.DriverconnectionURLjdbc:mysql://localhost:3306/crm userIdrootpassword1111 /jdbcConnection !-- 数据库连接配置 sqlserver--!--jdbcConnection driverClasscom.microsoft.sqlserver.jdbc.SQLServerDriverconnectionURLjdbc:sqlserver://gsdy.eicp.net:8633;databasenameqkmlsuserIdsapasswordsa20170410 /--!--jdbcConnection driverClassoracle.jdbc.OracleDriverconnectionURLjdbc:oracle:thin:127.0.0.1:1521:yycg userIdyycgpasswordyycg/jdbcConnection --!-- 默认false把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer为 true时把JDBC DECIMAL 和 NUMERIC 类型解析为java.math.BigDecimal --javaTypeResolverproperty nameforceBigDecimals valuefalse //javaTypeResolver!-- targetProject:生成PO类的位置 --javaModelGenerator targetPackagecom.ma.core.potargetProject.\src!-- enableSubPackages:是否让schema作为包的后缀 --property nameenableSubPackages valuefalse /!-- 从数据库返回的值被清理前后的空格 --property nametrimStrings valuetrue //javaModelGenerator!-- targetProject:mapper映射文件生成的位置 --sqlMapGenerator targetPackagecom.ma.mapper targetProject.\src!-- enableSubPackages:是否让schema作为包的后缀 --property nameenableSubPackages valuefalse //sqlMapGenerator!-- targetPackagemapper接口生成的位置 --javaClientGenerator typeXMLMAPPERtargetPackagecom.ma.core.dao targetProject.\src!-- enableSubPackages:是否让schema作为包的后缀 --property nameenableSubPackages valuefalse //javaClientGenerator!-- 指定数据库表 --table tableNamecustomer schema/table tableNamesys_user schema/table tableNamebase_dict schema/!-- table schema tableNameT_Qk_Orders/tabletable schema tableNameT_Qk_Orderitem/tabletable schema tableNameT_Qk_Amount/table --!--table schema tableNametb_content/tabletable schema tableNametb_content_category/tabletable schema tableNametb_item/tabletable schema tableNametb_item_cat/tabletable schema tableNametb_item_desc/tabletable schema tableNametb_item_param/tabletable schema tableNametb_item_param_item/tabletable schema tableNametb_order/tabletable schema tableNametb_order_item/tabletable schema tableNametb_order_shipping/tabletable schema tableNametb_user/table --/context
/generatorConfigurationGeneratorSqlmap.java使用代码
package com.ma.common.utils;import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.exception.XMLParserException;
import org.mybatis.generator.internal.DefaultShellCallback;public class GeneratorSqlmap {public void generator() throws Exception{ListString warnings new ArrayListString();boolean overwrite true;//指定 逆向工程配置文件File configFile new File(resource/generatorConfig.xml);ConfigurationParser cp new ConfigurationParser(warnings);Configuration config cp.parseConfiguration(configFile);DefaultShellCallback callback new DefaultShellCallback(overwrite);MyBatisGenerator myBatisGenerator new MyBatisGenerator(config,callback, warnings);myBatisGenerator.generate(null);} public static void main(String[] args) throws Exception {try {GeneratorSqlmap generatorSqlmap new GeneratorSqlmap();generatorSqlmap.generator();} catch (Exception e) {e.printStackTrace();}}}把上面的配置文件和代码放到一个可以运行的项目下运行就可以了。根据自己的需求配置不同的数据源和生成代码的位置。
commons-lang3
这个包中的很多工具类可以简化我们的操作在这里简单的研究其中的几个工具类的使用。 apache提供的众多commons工具包号称Java第二API而common里面lang3包更是被我们使用得最多的。因此本文主要详细讲解lang3包里面几乎每个类的使用希望以后大家使用此工具包写出优雅的代码