Table of contents
What are the advantages and what problems are solved
Create the first springboot project
Core configuration file application.yml or properties
Configuration items in application
The startup process of springboot
SSM framework based on springboot
SSMibatisPlus framework based on springboot
Packaging and running of springboot project
what is
Spring Boot is a new framework provided by the Pivotal team , which is designed to simplify the initial construction and development process of new Spring applications. The framework uses a specific approach to configuration, so that developers no longer need to define boilerplate configuration. In this way, Spring Boot aims to be a leader in the burgeoning field of rapid application development. -----From Baidu Encyclopedia
My understanding:
Springboot is the gospel of developers and a master of all common frameworks. Here is an example in life to illustrate:
The relationship between electrical appliances and plug-in boards:
I understand that springboot is like a big plug-in board, which can plug in various types of electrical appliances ( electrical appliances are various frameworks and middleware, etc. ), if we do not customize each electrical appliance, springboot will provide each socket Common settings have been made ( for example, the default socket is 220V, and the default plug can be inserted into several holes ), allowing developers to build projects with the least configuration and the least time when developing projects.
In addition, the springcloud project is based on the concept extended by springBoot. It can be said that there is no springcloud without springboot. The relevant tutorials about springboot will be updated in the follow-up editor.
What are the advantages and what problems are solved
Let's look at the description on the official website:
Features given on the official website:
1. Embed Tomcat, Jetty or Undertow directly (no need to deploy WAR files)
2. Provide insightful "starter" dependencies to simplify build configuration
3. Automatically configure Spring and third-party libraries as much as possible
4. Provides production-ready features such as metrics, health checks, and externalized configuration
5. Absolutely no code generation and no need for XML configuration
My experience:
1. Simplify the development process, and quickly build projects without XML configuration.
2. Simplify the development process, and quickly import the dependencies required by the project with the starter.
3. Simplify the packaging and operation and maintenance process. The internal nested server can be directly packaged and run without relying on external application servers.
4. A configuration class is provided, which can be developed in combination with any popular framework on the market.
Create the first springboot project
There are two ways to build a springboot project:
1. You can quickly build your first springboot project through the official website.
2. You can quickly build a springboot project through idea. Here is the recommended way to create idea.
Create a springboot project through idea:
1. Click new-project, select spring initializr, and fill in the information.
2. Select the version and dependencies of springboot, and click Finish to complete.
3. Modify the address of maven, change it to the local installation address, file-settings-input maven
4. Create the controller, service layer and code to start the helloworld journey.
controller code:
@RestController
public class HelloController {
@Autowired
HelloService helloService;
@RequestMapping("hello")
public String hello(){
return helloService.hello();
}
}
Service code:
public interface HelloService {
String hello();
}
Service implementation class code:
@Service
public class HelloServiceImpl implements HelloService {
@Override
public String hello() {
return "Hello World!";
}
}
5. Run the project and access the interface in the browser.
6. Access interface, here I specified the port of the project as 8099 in application.properties
7. The access interface information is as follows:
starter
When creating the springboot project, we checked the dependent projects. Let's take a look at the pom file:
What is this starter? We can click in with ctrl + left mouse button to see.....
It can be seen that springboot's web-starter dependency directly introduces four dependencies, which can greatly save us the time to find dependencies and versions of various frameworks, and quickly build projects, and the starter provided by springboot is not only web. , and there are all kinds of general frameworks, everything that one expects to find, does it feel cool to think about it?
Core configuration file application.yml or properties
In springboot, we provide us with a core configuration file, which is application. You can name it application.properties , or you can name it application.yml or application.yaml . The three naming methods all represent that it is springboot Core configuration file.
Configuration items in application
There are some commonly used configuration items in application, such as configuring database information:
spring.datasource.driver-class-name=
spring.datasource.url=
spring.datasource.username=
spring.datasource.password=
For example, configure the project access root path:
server.servlet.context-path=
For example, configure the port and access path of the project:
server.port=8099
#配置完毕后,需要访问时加上此项 例如:原来是http://localhost:8080
#现在是http://localhost:8080/springboot01
server.servlet.context-path=/springboot01
More configuration content can be obtained by accessing the address ( just search with ctrl+f if you need anything ):
The startup process of springboot
custom banner
The banner output at startup can be customized:
Add a banner.txt file under resources, enter the content of the file, and the content of the file can be generated by the website and pasted into the file: https://www.bootschool.net/ascii
Integrated log printing
Add the file logback.xml directly in the resources directory
<?xml version="1.0" encoding="UTF-8" ?>
<configuration>
<!--定义日志文件的存储地址 勿在 LogBack 的配置中使用相对路径-->
<property name="LOG_HOME" value="${catalina.base}/logs/" />
<!-- 控制台输出 -->
<appender name="Stdout" class="ch.qos.logback.core.ConsoleAppender">
<!-- 日志输出格式 -->
<layout class="ch.qos.logback.classic.PatternLayout">
<!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符-->
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n
</pattern>
</layout>
</appender>
<!-- 按照每天生成日志文件 -->
<appender name="RollingFile" class="ch.qos.logback.core.rolling.RollingFileAppender">
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!--日志文件输出的文件名-->
<FileNamePattern>${LOG_HOME}/server.%d{yyyy-MM-dd}.log</FileNamePattern>
<MaxHistory>30</MaxHistory>
</rollingPolicy>
<layout class="ch.qos.logback.classic.PatternLayout">
<!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符-->
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n
</pattern>
</layout>
<!--日志文件最大的大小-->
<triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
<MaxFileSize>10MB</MaxFileSize>
</triggeringPolicy>
</appender>
<!-- 日志输出级别和日志的输出方式 -->
<root level="info">
<appender-ref ref="Stdout" />
<!-- <appender-ref ref="RollingFile" />-->
</root>
<logger name="com.msb.mapper" level="DEBUG"></logger>
<!--日志异步到数据库 -->
<!--<appender name="DB" class="ch.qos.logback.classic.db.DBAppender">
日志异步到数据库
<connectionSource class="ch.qos.logback.core.db.DriverManagerConnectionSource">
连接池
<dataSource class="com.mchange.v2.c3p0.ComboPooledDataSource">
<driverClass>com.mysql.jdbc.Driver</driverClass>
<url>jdbc:mysql://127.0.0.1:3306/databaseName</url>
<user>root</user>
<password>root</password>
</dataSource>
</connectionSource>
</appender> -->
</configuration>
Integrate druid data sources
Import druid's dependencies
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>
Add configuration information in application.yml:
spring:
datasource:
# 使用阿里的Druid连接池
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
# 填写你数据库的url、登录名、密码和数据库名
url: jdbc:mysql://127.0.0.1:3306/mydb?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
username: root
password: root
druid:
# 连接池的配置信息
# 初始化大小,最小,最大
initial-size: 5
min-idle: 5
maxActive: 20
# 配置获取连接等待超时的时间
maxWait: 60000
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
timeBetweenEvictionRunsMillis: 60000
# 配置一个连接在池中最小生存的时间,单位是毫秒
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
# 打开PSCache,并且指定每个连接上PSCache的大小
poolPreparedStatements: true
maxPoolPreparedStatementPerConnectionSize: 20
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
filters: stat,wall,slf4j
# 通过connectProperties属性来打开mergeSql功能;慢SQL记录
connectionProperties: druid.stat.mergeSql\=true;druid.stat.slowSqlMillis\=5000
# 配置DruidStatFilter
web-stat-filter:
enabled: true
url-pattern: "/*"
exclusions: "*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*"
# 配置DruidStatViewServlet
stat-view-servlet:
url-pattern: "/druid/*"
# IP白名单(没有配置或者为空,则允许所有访问)
allow: 127.0.0.1,192.168.8.109
# IP黑名单 (存在共同时,deny优先于allow)
deny: 192.168.1.188
# 禁用HTML页面上的“Reset All”功能
reset-enable: false
# 登录名
login-username: admin
# 登录密码
login-password: 123456
handle exception
When an exception occurs in the background interface, a blank page prompt will appear, which is very unfriendly. At this time, you can use the exception handling of springboot to configure the error information page.
The usage is as follows:
You can customize the exception handling class and specify which exceptions jump to which pages
1. Add Springboot interceptor:
@Component
public class DemoInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("执行拦截器");
return true;
}
}
2. Configure the interceptor
Note: The class is annotated @Configuration. This class is equivalent to a SpringMVC configuration file.
addPathPattern(): Which URLs to intercept. /** intercept all
excludePathPatterns(): Which URLs are not blocked. When conflicting with addPathPattern(), excludePathPatterns() takes effect.
@Configuration
public class MyConfig implements WebMvcConfigurer {
@Autowired
private DemoInterceptor demoInterceptor;
//配置拦截器的映射
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(demoInterceptor).addPathPatterns("/**").excludePathPatterns("/login");
}
}
Commonly used annotations
@SrpingBootApplication:
The core annotation on the startup class, which contains three annotations:
- SpringBootConfiguration is equivalent to configuration
- EnableAutoConfiguration Autowiring
- ComponentScan package scan
Configuration
@Configuration
Specify the current class as the configuration class of springboot. You can define the @Bean annotation in the configuration class, inject the bean object, and hand the bean object to springboot for management.
Configuration(proxyBeanMethods=true)
proxyBeanMethods=true: Represents a single instance that relies on the spring container to control the Bean through the proxy object
proxyBeanMethods=false: represents that the singleton of the Bean will not be controlled through the proxy object
Import
@Import: Added to the class, other classes can be introduced through this annotation.
conditional
@Conditional: Component injection is performed if the conditions in conditional are met
@ImportResource: Allows us to define xml configuration files and configure beans in the files, as follows:
ConfigruationProperties
Read the content in the configuration file and inject it into a specific class in the form of an object
@ ConfigruationProperties
SSM framework based on springboot
1. Create a project, please refer to the chapter: Create the first springboot project
2. Import dependencies
<!--日志包-->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.6.1</version>
</dependency>
<!--代码生成工具-->
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.2</version>
</dependency>
<!-- 分页插件 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.4.1</version>
</dependency>
3. Configure application.yml
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: 123456
url: jdbc:mysql://127.0.0.1:3306/test?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true
thymeleaf:
prefix: classpath:/templates/html/
suffix: .html
cache: false
model: HTML5
encoding: UTF-8
mybatis:
type-aliases-package: com.ssm.mapper
mapper-locations: classpath:com/ssm/mapper/*.xml
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
server:
port: 8099
4. Add a new file generatorConfig.xml, you need to modify the path in the file.
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE generatorConfiguration PUBLIC
"-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<classPathEntry
location="D:\maven\repository\mysql\mysql-connector-java\8.0.22\mysql-connector-java-8.0.22.jar"/>
<context id="testTables" targetRuntime="MyBatis3">
<commentGenerator>
<!-- 是否去除自动生成的注释 true:是 : false:否 -->
<property name="suppressAllComments" value="true"/>
</commentGenerator>
<!--数据库连接的信息:驱动类、连接地址、用户名、密码 -->
<!--<jdbcConnection driverClass="${jdbc.driver}"--> <!--connectionURL="${jdbc.url}"--> <!--userId="${jdbc.username}"--> <!--password="${jdbc.password}">--> <!--</jdbcConnection>-->
<jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
connectionURL="jdbc:mysql://127.0.0.1:3306/test?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true"
userId="root" password="">
</jdbcConnection>
<!-- 默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer,为 true时把JDBC DECIMAL 和 NUMERIC 类型解析为java.math.BigDecimal -->
<javaTypeResolver>
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
<!-- targetProject:生成PO类的位置 -->
<javaModelGenerator targetPackage="com"
targetProject="F:\code">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false"/>
<!-- 从数据库返回的值被清理前后的空格 -->
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<!-- targetProject:mapper映射文件生成的位置 -->
<sqlMapGenerator targetPackage="com"
targetProject="F:\code">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false"/>
</sqlMapGenerator>
<!-- targetPackage:mapper接口生成的位置 -->
<javaClientGenerator type="XMLMAPPER" targetPackage="com"
targetProject="F:\code">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false"/>
</javaClientGenerator>
<!-- 指定数据库表 -->
<table tableName="gameuser" domainObjectName="Gameuser"
enableCountByExample="false"
enableUpdateByExample="false"
enableDeleteByExample="false"
enableSelectByExample="false"
selectByExampleQueryId="false">
</table>
<!-- 有些表的字段需要指定java类型
<table tableName="area" domainObjectName="Area"
enableCountByExample="false"
enableUpdateByExample="false"
enableDeleteByExample="false"
enableSelectByExample="false"
selectByExampleQueryId="false">
</table>
-->
</context>
</generatorConfiguration>
5. Add log4j.properties
log4j.rootLogger=debug,stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.err
log4j.appender.stdout.layout=org.apache.log4j.SimpleLayout
log4j.appender.logfile=org.apache.log4j.FileAppender
log4j.appender.logfile.File=d:/lc.log
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d(yyyy-MM-dd HH:mm:ss)%1 %F %p %m%n
6. Add a new java class under the test package:
import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultShellCallback;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class GeneratorCode {
public void generator() throws Exception {
List<String> warnings = new ArrayList<String>();
boolean overwrite = true;
File configFile = new File("F:\\springbootall\\sp03\\ssm01\\target\\classes\\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) {
GeneratorCode generatorSqlmap = new GeneratorCode();
try {
generatorSqlmap.generator();
} catch (Exception e) {
e.printStackTrace();
}
}
}
7. Run the java class to generate code.
8. The code of the Controller class is as follows:
@RequestMapping(value = "getAllGameUserList",method = RequestMethod.GET)
public Map<String,Object> getAllGameUsers(
@RequestParam(value = "currentPage",required = false) int currentPage,
@RequestParam(value = "pageSize",required = false) int pageSize,
@RequestParam(value = "recordCount",required = false) int recordCount,
@RequestParam(value = "usrLoginNm",required = false) String usrLoginNm,
@RequestParam(value = "usrNm",required = false) String usrNm,
@RequestParam(value = "usrCardNum",required = false) String usrCardNum,
@RequestParam(value = "usrAddr",required = false) String usrAddr,
@RequestParam(value = "usrBirDate",required = false) Date usrBirDate,
@RequestParam(value = "usrHobby",required = false) String usrHobby,
@RequestParam(value = "usrDetail",required = false) String usrDetail){
Gameuser gameuser=new Gameuser();
gameuser.setUsrLoginNm(usrLoginNm);
gameuser.setUsrNm(usrNm);
gameuser.setUsrCardNum(usrCardNum);
gameuser.setUsrAddr(usrAddr);
gameuser.setUsrBirDate(usrBirDate);
gameuser.setUsrHobby(usrHobby);
gameuser.setUsrDetail(usrDetail);
logger.info("gameuser: "+gameuser.toString());
PageInfo<Gameuser> gameuserPage = gameUserService.getAllGameUsers(currentPage, pageSize, recordCount, gameuser);
Map<String,Object> objectMap=new HashMap<>();
objectMap.put("recordList",gameuserPage.getList());
objectMap.put("totalCount",gameuserPage.getTotal());
objectMap.put("currentPage",gameuserPage.getPageNum());
objectMap.put("pageSize",gameuserPage.getPageSize());
return objectMap;
}
9. The ServiceImpl code is as follows:
@Override
public PageInfo<Gameuser> getAllGameUsers(int currentPage, int pageSize, int recordCount, Gameuser gameuser) {
PageHelper.startPage(currentPage, pageSize);
List<Gameuser> allGameUserLists = gameuserMapper.getAllGameUserLists(gameuser);
PageInfo<Gameuser> gameuserPageInfo = new PageInfo<>(allGameUserLists);
return gameuserPageInfo;
}
10. The Mapperxml code is as follows:
<select id="getAllGameUserLists" parameterType="com.ssm.bean.Gameuser" resultType="com.ssm.bean.Gameuser">
SELECT * FROM gameuser
<where>
<if test="usrLoginNm != null and usrLoginNm != ''" >
<bind name="usrLoginNmPattern" value="'%'+usrLoginNm+'%'"/>
and usrLoginNm like #{usrLoginNmPattern}
</if>
<if test="usrNm != null and usrNm != ''" >
<bind name="usrNmPattern" value="'%'+usrNm+'%'"/>
and usrNm like #{usrNmPattern}
</if>
<if test="usrCardNum != null and usrCardNum != ''" >
and usrCardNum = #{usrCardNum}
</if>
<if test="usrAddr != null and usrAddr != ''" >
<bind name="usrAddrPattern" value="'%'+usrAddr+'%'"/>
and usrAddr like #{usrAddrPattern}
</if>
<if test="usrBirDate != null and usrBirDate != ''" >
and usrAddr = #{usrBirDate}
</if>
<if test="usrHobby != null and usrHobby != ''" >
and usrHobby = #{usrHobby}
</if>
<if test="usrDetail != null and usrDetail != ''" >
<bind name="usrDetailPattern" value="'%'+usrDetail+'%'"/>
and usrDetail like #{usrDetailPattern}
</if>
</where>
</select>
SSMibatisPlus framework based on springboot
See my other blog for details: MybatisPlus detailed tutorial, you won’t hit me after reading it......_Only for code drunk blog-CSDN Blog
Packaging and running of springboot project
Through the maven-install command, the project is packaged, and the packaged jar package is stored in the target directory:
Place it directly on the machine with JDK and execute the command:
java -jar jar package name
You can run the project.