目录
Spring Boot一点背景
简而言之:化繁为简,开发配置部署监控都变得简单了,抛弃了繁琐的xml配置过程。
官网上赋予的Spring Boot的特性:
- Create stand-alone Spring applications
- Embed Tomcat, Jetty or Undertow directly (no need to deploy WAR files)
- Provide opinionated 'starter' dependencies to simplify your build configuration
- Automatically configure Spring and 3rd party libraries whenever possible
- Provide production-ready features such as metrics, health checks, and externalized configuration
- Absolutely no code generation and no requirement for XML configuration
Spring Boot的核心模块:
- 自动配置:自动配置spring的相关属性
- 起步依赖:告诉spring boot需要什么功能,就自动约会
- 执行器:健康检查
- 可选的命令行界面
可以尝试:博客:在eclipse上创建Spring项目的插件。使用这个插件可以更方便的进行项目的创建,直接生成对应的pom.xml文件
Spring项目结构
一个刚生成的Spring项目结构如下图:
其中,resource文件夹下面,application.properities是配置文件,static放静态资源,template放模板资源。
在根下,mvnw是Maven的脚本文件,删除也不影响运行,.cmd的是Windows下的,不带.cmd的是Linux下的。
pom.xml
在pom.xml里面有这些:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.0.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
这个地方是Maven里面的,继承spring boot的父级项目:spring-boot-starter-parent。有了这部分才能算是一个spring boot的项目,spring-boot-starter-parent 是一个特殊的 starter ,它用来提供相关的 Maven 默认依赖,使用它之后,常用的包依赖就可以省去 version 标签。
打开父级依赖的父级依赖(Ctrl+左键),可以看到里面有很多库和对应的版本,如果想采用其他版本可以在里面进行修改。
在<dependencies>下是项目的依赖,其中:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
是开发web项目的起步依赖;
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
是测试的起步依赖;
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
是spring boot提供的项目编译打包插件。
main方法
在demoApplication.java里面有一个main()方法:
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@SpringBootApplication代表是一个spring boot的应用程序,这个注解可以开启spring的自动配置
@SpringBootApplication 是 Spring Boot 的核心注解,它是一个组合注解,该注解组合了:@Configuration、@EnableAutoConfiguration、@ComponentScan; 若不是用 @SpringBootApplication 注解也可以使用这三个注解代替。
其中,@EnableAutoConfiguration 让 Spring Boot 根据类路径中的 jar 包依赖为当前项目进行自动配置,例如,添加了 spring-boot-starter-web 依赖,会自动添加 Tomcat 和 Spring MVC 的依赖,那么 Spring Boot 会对 Tomcat 和 Spring MVC 进行自动配置。
Spring Boot 还会自动扫描 @SpringBootApplication 所在类的同级包以及下级包里的 Bean ,所以入口类建议就配置在 grounpID + arctifactID 组合的包名下(这里为 com.xpwi.springboot 包)
controller的方法要跟application同级或在下级,否则可能扫描不到。
配置文件
有两种配置文件都可以使用:appliction.properties和applications.yml
配置文件可以放在这样四个地方,根据优先级分别是:
- 当前项目根目录下的config目录下 /config/
- 当前项目的根目录下 /
- resources目录下的config目录下 /src/main/resources/config/
- resources目录下 /src/main/resources/
Spring Boot启动,默认会从这四个位置按顺序去查找相关属性并加载。
采用application.properities
例如:
application.properties
server.port=8080
server.context-path=/test
这样在访问时需要http://127.0.0.1:8080/test/hello
上下文默认是一个斜杠/,可以手动修改。
采用application.yml
直接把 .properties 后缀的文件删掉,使用.yml文件来进行简单的配置
例如:
server.port : 8080
name : mxb
url : https://blog.csdn.net/mxb1234567
(注意:冒号:后面要有一个空格)
那么在使用时可以采用:
@Value("${name}")
String name;
来获取配置文件中的数据,相关知识参考了博客:SpringBoot 注解@Value的各种条件下使用方法
yml文件也可以这样:
server:
port:8080
context-path:/test
多配置文件
多个环境产生多个配置文件,如测试配置文件、开发配置文件。在实际项目开发中很常见。
后来配置的配置文件可以在总的配置文件里面进行激活。
如:
存在多个配置文件:
application.properties
application-dev.properties
application-test.properties
在dev的配置文件中采用9090端口,test采用8090端口
那么在总的application.properties里面可以采用:
spring.profiles.active=dev
对application-dev.properties的进行激活,这样在访问资源时需要访问9090端口。
注意:如果总的配置文件和被激活的都配置了同一属性,则优先使用被激活的。
自定义配置文件
例如:
在配置文件中写入一些属性:
boot.name=mxb
boot.url=https://blog.csdn.net/mxb1234567
可以自己读取这个值
在controller中,可以采用@Value("${boot.name}")读取这个值:
@Value("${boot.name}")
private String name;
@Value("${boot.url}")
private String url;
@RequestMapping("/hello")//意思是请求/hello方法下的,改成/me/hello则要访问http://127.0.0.1:9090/mxb/hello,后面会讲Spring Boot注解
public @ResponseBody String config()
{
return name + "---" + url;
}
如果在尝试的过程中出现了乱码可以尝试在application.properities加入:
spring.http.encoding.charset=UTF-8
spring.http.encoding.enable=true
spring.http.encoding.force=true
自定义配置的另外一种策略:定义一个类
定义一个类:
Info.java
@Component//变成spring的一个组件
@ConfigurationProperties(prefix="boot")
public class info
{
private String name;
private String url;
public String getName()
{
return name;
}
public String getUrl()
{
return url;
}
}
技巧:eclipse中可以右键类文件,source->Generate Getters and Setters生产get和set方法
在其他地方使用时,可以采用:
@Autowired
private Info myinfo;
那么信息就读取到了myinfo中。
Spring Boot下的Spring MVC
一些注解:
@Controller
@RestController
spring4之后新增的,是@Controller和@ResponseBody的组合注解,返回字符串或者json
@GetMapping
RequestMapping+RequestMethod="get",所以只支持get方法
@PostMapping
RequestMapping+RequestMethod="post",所以只支持post方法,表单提交可以是post方法,如果在浏览器里面请求是get方法,采用这种方法会提示405
@PutMapping
很少使用,put方法一般是修改方法,可以用post代替
@DeleteMapping
很少使用,删除数据,可以用@GetMapping代替
注意:这些注解并不是Spring Boot的而是Spring和Spring MVC带的
@RequestMapping返回的是一个json
SpringBoot使用JSP
采用下面几个步骤:
1.在使用的时候要在pom.xml里面加入Tomcat对JSP的解析包
pom.xml
<!-- tomcat的支持.-->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
<!-- servlet依赖. -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
</dependency>
<!-- jsp依赖 -->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
</dependency>
<!-- jstl标签依赖 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
注意:jspl在父级项目里面有版本号,所以不用加
2.在application.properties配置spring MVC的视图展示为jsp
application.properties
spring.mvc.view.prefix=/
spring.mac.view.suffix=.jsp
其中符号/表示直接在根下,也可以放在例如/WEB-INF/jsp下
3.在src/main下创建一个webapp目录,然后新建jsp界面
在使用JSPController的时候:
JSPController.java
@Controller
public class JSPController {
@GetMapping("/index")
public String index(Model m)
{
m.addAttribute("now","spring boot 集成 jsp");
return "index";
}
}
Spring Boot集成mybatis
MyBatis 是一个框架,它支持自定义 SQL、存储过程以及高级映射。MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。
在使用时可以采用:
1.在pom.xml里面加入mybatis的依赖
pom.xml
<!-- mybatis依赖 -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.1</version>
</dependency>
<!-- mysql的jdbc依赖 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
2.在application.properties里面配置Mybatis的Mapper.xml文件所在位置:
mybatis.mapper-locations=classpath:com/mxb/springboot/mapper/*.xml
3.在application.properties里面配置数据库的连接信息
application.properties
spring.datasource.username=root
spring.datasource.password=515257
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc://mysql://localhost:3306/springboottest?userUnicode=true&characterEncoding=utf8&useSSL=false
4.在Mapper接口中添加@Mapper注解或者在运行的主动类上添加@MapperScan("com.mxb.springboot.mapper")注解包扫描。
事务支持
在入口类上加入@EnableTransactionManagement
在访问数据库的Service的方法上加上@Transaction表示事务的支持,当程序异常退出时会自动进行回滚
RESTFull(未完待续)
是一种软件架构设计风格,并不是标准。
例如访问一个网站:http://localhost:8080/api/order?id=1000&name=mxb
使用RESTFull风格则是:http://localhost:8080/api/order/1000/mxb
spring boot 开发RESTFull:
采用注解@PathVariable
例如在controller中:
HelloController.java
//http://127.0.0.1:8080/mxb/hello/10086/mxb
@RequestMapping("/mxb/hello/{id}/{name}")
public String hello(@PathVariable("id") Integer id,@PathVariable("name") String name) {
return "Hellomxb" + id + name;
}
访问http://127.0.0.1:8080/mxb/hello/10086/mxb的打印结果就是:
Hellomxb10086mxb
Spring Boot实现Filter(未完待续)
方法一:普通filter
1.写一个注解过滤器
MyFilter.java
@WebFilter(urlPatterns="/*")
public class MyFilter implements Filter
{
@Override
public void init(FilterConfig filterConfig) throws ServletException
{}
@Override
public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain)
throws IOException,ServletException
{
System.out,println("filter过滤器");
chain.doFilter(request,response);
}
@Override
public void destory()
{}
}
2.在main方法的主类上添加注解:
DemoApplication.java
@ServletComponentScan(basePackages={"com.mxb.demo.filter"})
由于filter设置的是所有的都过滤,因此我们任意打开一个界面,可以看到下图:
方法二:写一个配置类,把filter注入进来(未完待续)
我们新建一个class名字SecondFilter
在config文件中,如ServletConfig.java:
注意:也要放在main方法的同级或在子目录下,否则可能扫描不到。