SpingBoot学习笔记
之前学习的框架主要有ssh、ssm以及分布式以及分布式集群方面的知识,之后也一直想学习SpringBoot框架,无奈于没有多余的时间,正好实习的公司有用到SpringBoot框架,抽空学习了一下,知识点肯定不全,也是挑重点去学习了一下。之后肯定会慢慢去学习不知道的东西,必须要知根知底!!!下面的内容也是本人的笔记,若有错误,欢迎指出 。
1. 什么是SpringBoot
Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程。该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置。通过这种方式,Spring Boot致力于在蓬勃发展的快速应用开发领域(rapid application development)成为领导者。(百度百科)
上边说到的特定的方式其实就是Java配置的方式,即注解方式,目的主要是为了简化Spring项目开发中文件配置的繁琐性,环境搭建难,第三方技术整合困难等问题,使用SpringBoot可以极大的加快开发效率,使得开发人员专注于项目的开发,不用花太多的时间进行项目环境的搭建,第三方技术的整合,项目部署(内嵌Tomcat)的时间上的浪费。
2. Spring的Java配置方式
在之前的项目开发中,使用配置文件的方式去配置bean,即<bean></bean>
,这里我们使用@Bean注解来进行配置
下面使用到的关键注解为@Bean
、@Configuration
、@ComponentScan
@Configuration
可以理解为我们之前的配置文件,代表该类是个配置类
@ComponentScan(basePackages="xxx.xxx")
即扫描器,用于扫描指定的包,若不指定,默认扫描本包以及子包
下面我们看个示例
Dao层(模拟)
package com.tqb.dao;
import com.tqb.pojo.Student;
public class StudentDao {
public void getStudent(){
Student student = new Student();
student.setName("zhangsan");
student.setAge(22);
System.out.println(student);
}
}
Service层
package com.tqb.service;
import com.tqb.dao.StudentDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class StudentService {
@Autowired
private StudentDao dao;
public void getStudent(){
dao.getStudent();
}
}
配置类
package com.tqb.config;
import com.tqb.dao.StudentDao;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration// 相当于配置文件
@ComponentScan(basePackages = "com.tqb")// 扫描包
public class StudentConfig {
// 将StudentDao加载到Spring容器中
@Bean// 相当于配置文件中的bean
public StudentDao getStudentDao(){
return new StudentDao();
}
}
测试类
package com.tqb.test;
import com.tqb.config.StudentConfig;
import com.tqb.service.StudentService;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class TestClass {
public static void main(String[] args) {
// 获取容器对象 这里不适用配置文件所有不是之前的ClassPathXmlApplicationContext了
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(StudentConfig.class);
StudentService studentService = context.getBean(StudentService.class);
studentService.getStudent();
context.destroy();// 销毁容器
}
}
3. 读取外部配置文件
主要注解:
@PropertySource
:用于导入properties和ym文件
@ImportResource
:用于导入xml文件
@Value
:用于读取配置文件中的键值对的值
//第二个参数的意思为若文件不存在,则不报错
@PropertySource(value = {"classpath:jdbc_test.properties", "xxx.properties"}, ignoreResourceNotFound = true)
@ImportResource(value = {"classpath:application.xml"})
@Value("${mysql.driver}")
private String driver;
@Value("${mysql.url}")
private String url;
@Value("${mysql.username}")
private String username;
@Value("${mysql.driver}")
private String password;
4. 第一个SpringBoot应用
主要注解:
@Controller
:默认大家了解
@Configuration
:上边有讲,相当于一个配置文件的标识
@SpringBootApplication
:SpringBoot应用
项目准备:在pom文件中添加如下内容
设置parent:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.2.RELEASE</version>
</parent>
导入web支持
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
设置maven插件(非必须)用于maven方式启动项目、
命令:spring-boot:run
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
示例:
package com.application;
import org.springframework.boot.Banner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@Configuration
@SpringBootApplication
public class StudentApplication {
@RequestMapping("hello")
@ResponseBody
public String helloworld(){
return "hello world";
}
public static void main(String[] args) {
SpringApplication.run(StudentApplication.class, args);
}
}
5. SpringBootApplication注解
打开@SpringBootApplication
的源码我们可以看到,该注解还被以下几个主要注解标识
@SpringBootConfiguration
:和@Configuration
类似,并且我们看到,在@SpringBootConfiguration
的源码中,依然被@Configuration
标识,代表它也是个配置类。@EnableAutoConfiguration
:它是SpringBoot中一个重要的注解,负责自动化配置,我们知道SpringBoot中集成了非常多的第三方技术,我们使用这些技术不需要进行技术之间的整合,我们只需要导入我们需要的依赖就可以使用,这也是SpringBoot的优点,通过这个注解将我们需要的类进行自动化的注入到Spring容器中。并且在@EnableAutoConfiguration
的注解中,@Import(EnableAutoConfigurationImportSelector.class)
正是通过这个注解实现bean的注入。@ComponentScan
:就是我们上边说的包的扫描。- 补充:在
@SpringBootApplication
中使用属性exclude可以关闭具体类的自动化配置,如:@SpringBootApplication(exclude = RedisAutoConfiguration.class)
,表示不再对Redis进行自动化的配置了。
6. 全局配置文件
SpringBoot中集成了非常多的第三方技术,既然集成了这么多的技术,必须需要进行一些配置,SpringBoot就提供了全局配置文件。配置文件有两种:application.properties、application.yml
这里对yml文件可能感觉到陌生,其实它和properties是差不多的,只不过格式有些不同,这里我不加介绍,感兴趣的同学可以自己查询了解。
示例*(application.yml):
server:
# 访问端口 默认端口8080
port: 8099
# 访问路径格式设置 默认 /
servlet-path: "*.html"
全局配置文件:点击下载
7. 官方提供的starter pom
8. 日志
# LOGGING
logging.config= # Location of the logging configuration file. For instance `classpath:logback.xml` for Logback
logging.exception-conversion-word=%wEx # Conversion word used when logging exceptions.
logging.file= # Log file name. For instance `myapp.log`
logging.level.*= # Log levels severity mapping. For instance `logging.level.org.springframework=DEBUG`
logging.path= # Location of the log file. For instance `/var/log`
logging.pattern.console= # Appender pattern for output to the console. Only supported with the default logback setup.
logging.pattern.file= # Appender pattern for output to the file. Only supported with the default logback setup.
logging.pattern.level= # Appender pattern for log level (default %5p). Only supported with the default logback setup.
logging.register-shutdown-hook=false # Register a shutdown hook for the logging system when it is initialized.
9. 静态资源
在SpringBoot中,没有进行配置时默认可以对webapp的目录进行访问,一般来说,要求对静态资源的访问做出限制
spring:
resources:
static-locations: classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/
10. 自定义消息转化器(默认的消息转化器编码为utf-8)
@Bean
public StringHttpMessageConverter stringHttpMessageConverter(){
StringHttpMessageConverter converter = new StringHttpMessageConverter(Charset.forName("UTF-8"));
return converter;
}
11. 自定义***
- @Configuration注解
- 继承WebMvcConfigurerAdapter类
- 重写addInterceptors
- 实现HandlerInterceptor
- 注册
注意,若自定义mvc的类和启动类不在同一包或者非子包,需要进行注册
package com.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Configuration
public class MySrpingMVCConfig extends WebMvcConfigurerAdapter {
@Override
public void addInterceptors(InterceptorRegistry registry) {
HandlerInterceptor handlerInterceptor = new HandlerInterceptor() {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("pre...");
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("post...");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("after...");
}
};
registry.addInterceptor(handlerInterceptor).addPathPatterns("/**");// 过滤所有
}
}
@SpringBootApplication(scanBasePackages={"com.application","com.config"},exclude = RedisAutoConfiguration.class)
12. 事务
主要注解
@Transaction
:可加类或者具体的方法,加到类上表示对所有的public方法进行事务管理
在SpringBoot中,使用事务需要导入jdbc的依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
13. 视图解析器配置与jsp-404问题
对视图解析器进行配置时,推荐使用全局配置文件进行配置
spring.mvc.view.prefix= # Spring MVC view prefix.
spring.mvc.view.suffix= # Spring MVC view suffix.
在SpringBoot中,内嵌的Tomcat不建议使用jsp,所以会出现404的问题,如果要使用,需要导入依赖
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
14. 对SpringBoot发布到独立的Tomcat
- 设置为provided是在打包时会将该包排除,因为要放到独立的tomcat中运行,是不需要的
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
- 修改启动类
- 继承SpringBootServletInitializer
- 重写configure()方法
package com.application;
import org.springframework.boot.Banner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@Configuration
// excldue:关闭自动配置
@SpringBootApplication(scanBasePackages={"com.application","com.config"},exclude = RedisAutoConfiguration.class)//@ComponentScan// 默认同级目录以及子目录都会进行扫描
public class StudentApplication extends SpringBootServletInitializer {
@RequestMapping("hello")
@ResponseBody
public String helloworld(){
return "hello world";
}
public static void main(String[] args) {
SpringApplication.run(StudentApplication.class, args);
}
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(StudentApplication.class);
}
}
彩蛋
大家在启动项目的时候有没有发现有这样一个东西
这个是可以修改的哦
在resources目录下创建一个banner.txt文件,添加一个自己的banner
像下面这样
生成banner的网址:http://patorjk.com/software/taag/#p=display&h=3&v=3&f=4Max&t=Bobo
如果都不喜欢的话可以进行关闭:
public static void main(String[] args) {
// 关闭banner 设置Banner样式在resources路径下创建banner.txt
SpringApplication application = new SpringApplication(StudentApplication.class);
application.setBannerMode(Banner.Mode.OFF);
application.run(args);
}