首页 > 其他分享 >SpringBoot简单使用(2)

SpringBoot简单使用(2)

时间:2022-09-01 21:34:48浏览次数:40  
标签:return SpringBoot name void 简单 class 使用 public String

1.2.7:CommandLineRunner 接口:

开发中可能会有这样的情景。需要在容器启动后执行一些内容。比如读取配置文件,数 据库连接之类的。SpringBoot 给我们提供了两个接口来帮助我们实现这种需求。这两个接口 分别为 CommandLineRunner 和 ApplicationRunner。他们的执行时机为容器启动完成的时候。 这两个接口中有一个 run 方法,我们只需要实现这个方法即可。这两个接口的不同之处 在于: ApplicationRunner 中 run 方 法 的 参 数 为 ApplicationArguments , 而 CommandLineRunner 接口中 run 方法的参数为 String 数组

例子:定义接口:

public interface SomeService {
void sayHello(String name);
}

定义实现类:

@Service("someservice")
public class SomeServiceImpl implements SomeService{

@Override
public void sayHello(String name) {
System.out.println("欢迎"+name);
}
}

继承CommandLineRunner,实现run方法

@SpringBootApplication
public class Springboot01Application implements CommandLineRunner {

public static void main(String[] args) {

ApplicationContext context = SpringApplication.run(Springboot01Application.class, args);
SomeService sc =(SomeService) context.getBean("someservice");
sc.sayHello("李四");
}

@Override
public void run(String... args) throws Exception {
System.out.println("在容器对象创建好后执行的对象");
}
}

1.3:Spring Boot 和 web 组件

1.3.1:springboot拦截器:

Spring Boot 使用拦截器步骤: 1. 创建类实现 HandlerInterceptor 接口

public class LoginInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("执行了拦截器");
return true;
}
}

2. 注册拦截器对象

@Configuration  //相当于springmvc配置文件
public class MyAppConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
//指定拦截的地址
String path[]={"/user/**"};
//指定放行的地址
String excludePath[]={"/user/login"};
registry.addInterceptor(new LoginInterceptor())
.addPathPatterns(path)
.excludePathPatterns(excludePath);
}
}

3. 创建测试使用的 Controller

@RequestMapping("/user/login")
@ResponseBody
public String userlogin(HttpServletRequest request){

return "userlogin";
}
@RequestMapping("/user/regiest")
@ResponseBody
public String userreigest(HttpServletRequest request){

return "userregiest";
}

4:访问浏览器并观察:执行

/user/regiest

被拦截

 

1.3.2:Spring Boot 中使用 Servlet

1. 创建 Servlet:

    @Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req,resp);
}

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=uft-8");
PrintWriter writer = resp.getWriter();
writer.print("使用servlet对象");
writer.flush();
writer.close();
}
}

2. 注册 Servlet

@Configuration  
public class MyAppConfig {
@Bean
public ServletRegistrationBean servletRegistrationBean(){
ServletRegistrationBean bean = new ServletRegistrationBean(new MyServlet(),"/myservlet");
return bean;
}
}

3. 主启动类启动

4.启动主类,在浏览器中访问 

 

1.3.2:Spring Boot 中使用 Filter

  1.3.2.1:使用自己定义的过滤器

1.创建 Filter 对象

public class MyFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {

}

@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
System.out.println("使用过滤器");
filterChain.doFilter(servletRequest,servletResponse);
}

@Override
public void destroy() {

}
}

2.注册 Filter

@Configuration
public class FilterConfig {
@Bean
public FilterRegistrationBean registrationBean(){
FilterRegistrationBean bean = new FilterRegistrationBean();
bean.setFilter(new MyFilter());
bean.addUrlPatterns("/user/*");
return bean;
}
}

3.创建 Controller

@Controller
public class HelloSpringBoot {

@RequestMapping("/user/login")
@ResponseBody
public String userlogin(){
return "userloign";
}

}

4.启动应用, 在浏览器访问

 

  1.3.2.2 字符集过滤器的应用:

1.创建 Servlet,输出中文数据

public class MyServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req,resp);
}

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html");
PrintWriter writer = resp.getWriter();
writer.print("使用servlet对象");
writer.flush();
writer.close();
}
}

2)注册 Servlet 和 Filter

@Configuration
public class CFandServletConfig {
@Bean
public ServletRegistrationBean servletRegistrationBean(){
ServletRegistrationBean bean = new ServletRegistrationBean(new MyServlet(),"/myservlet");
return bean;
}
@Bean
public FilterRegistrationBean filterRegistrationBean(){
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
CharacterEncodingFilter filter = new CharacterEncodingFilter();
filter.setEncoding("utf-8");
filter.setForceEncoding(true);
filterRegistrationBean.setFilter(filter);
filterRegistrationBean.addUrlPatterns("/*");
return filterRegistrationBean;
}
}

3.在 application.properties , 禁用 Spring Boot 中默认启用的过滤器

server.servlet.encoding.enabled=false

4.启动主类,运行浏览器

 

1.3.2.4 也可以在 application.properties 文件中设置过滤器:Spring Boot 项目默认启用了 CharacterEncodingFilter, 设置他的属性就可以(这种最简单)

server.servlet.encoding.charset=utf-8

#强制 request, response 使用 charset 他的值 utf-8

server.servlet.encoding.force=true

这样不用注册字符编码过滤器了

 

 

 

1.4 创建 Spring Boot 项目

pom.xml:

 

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.2</version>
</dependency>

<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

<build>

<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>

 

配置数据源:application.properties

spring.datasource.username=root
spring.datasource.password=ztb
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver


server.port=9093

实体类

package com.ztb.pojo;

public class User {
private int id;
private String name;
private String pwd;

@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", pwd='" + pwd + '\'' +
'}';
}

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getPwd() {
return pwd;
}

public void setPwd(String pwd) {
this.pwd = pwd;
}

public User(int id, String name, String pwd) {
this.id = id;
this.name = name;
this.pwd = pwd;
}

public User() {
}
}

创建 Dao 接口

@Mapper
public interface UserMapper {
List<User> selectAll();
}

mapper 文件:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.ztb.mapper.UserMapper">
<select id="selectAll" resultType="com.ztb.pojo.User">
select * from user
</select>

</mapper>

service 接口

public interface UserService {
List<User> selectAll();
}

service 接口实现类

@Service
public class UserServiceImpl implements UserService{

@Resource
UserMapper userMapper;
@Override
public List<User> selectAll() {
return userMapper.selectAll();
}
}

controller 类

@Controller
public class UserController {
@Resource
UserService userService;

@RequestMapping("/user")
@ResponseBody
public String selectuser(){
List<User> list = userService.selectAll();
for (User user : list) {
System.out.println(user);
}
return "查询结果";
}
}

启动 Application 类, 浏览器访问

 

1.4.1 @MapperScan:在 Dao 接口上面加入@Mapper,需要在每个接口都加入注解。当 Dao 接口多的时候不方便。可以使用如下的方式解决。

1.去掉 StudentMapper 接口的上面的@Mapper 注解

2.在主类上面加入 @MapperScan()

@SpringBootApplication
@MapperScan(basePackages = "com.ztb.mapper")
public class Springboot02Application {

public static void main(String[] args) {
SpringApplication.run(Springboot02Application.class, args);
}

}

1.4.2 mapper 文件和 java 代码分开管理:

mapper 文件放在 resources 目录下, java 代码放在 src/main/java。

实现步骤: 在 resources 创建自定义目录,例如 mapper, 存放 xml 文件

把原来的 xml 文件剪切并拷贝到 resources/mapper 目录

在 application.properties 配置文件中指定映射文件的位置,这个配置只有接口和映 射文件不在同一个包的情况下,才需要指定。

mybatis.mapper-locations=classpath:mapper/*.xml
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

1.4.3事务支持:

Spring Boot 使用事务非常简单,底层依然采用的是 Spring 本身提供的事务管理

➢ 在入口类中使用注解 @EnableTransactionManagement 开启事务支持

➢ 在访问数据库的 Service 方法上添加注解 @Transactional 即可

步骤:修改 StudentService,在 addStudent()方法中抛出异常

@Override
@Transactional
public int adduser(User user) {
int i = userMapper.adduser(user);
int s=1/0;
return i;
}

在 Application 主类上,@EnableTransactionManagement 开启事务支持 @EnableTransactionManagement 可选,但是@Service 必须添加事务才生效

@SpringBootApplication
@MapperScan(basePackages = "com.ztb.mapper")
@EnableTransactionManagement
public class Springboot02Application {

public static void main(String[] args) {
SpringApplication.run(Springboot02Application.class, args);
}

}

测试应用, 数据没有添加成功

注释掉 StudentServiceImpl 上的@Transactional 测试。数据添加成功

标签:return,SpringBoot,name,void,简单,class,使用,public,String
From: https://www.cnblogs.com/zhangtaibing/p/16647894.html

相关文章

  • 【js】for 循环中使用 setTimeout 的问题
    问题:下面代码的输出结果不是间隔3秒依次输出1,2,3,4,5。而是隔了3秒连续输出6。这是为什么呢?for(vari=1;i<=5;i++){setTimeout(functiontimer(){......
  • leetcode 206. Reverse Linked List 反转链表(简单)
    一、题目大意给你单链表的头节点head,请你反转链表,并返回反转后的链表。示例1:输入:head=[1,2,3,4,5]输出:[5,4,3,2,1]示例2:输入:head=[1,2]输出:[2,1]示例3:......
  • [转]CMake与Make最简单直接的区别
    写程序大体步骤为:1.用编辑器编写源代码,如.c文件。2.用编译器编译代码生成目标文件,如.o。3.用链接器连接目标代码生成可执行文件,如.exe。但如果源文件太多,一个一个编译......
  • Springboot整合Sentinel实现流控
    在Springboot项目中整合Sentinel实现流控,Gateway整合Sentinel见Gateway整合Sentinel,Sentinel-daahboard的改造见Sentinel-dashboard改造(普通流控和网关流控规则持久化到Nac......
  • 正则表达式在Java中的使用
    正则表达式在Java中的使用不仅限于String类中的match()方法!!!正则中的^与$首先我们来了解这两个符号在正则表达式中的作用:^符号放在表达式头部表示开始匹配$符号放......
  • Redis使用 Redis封装
    封装Redis:一、application.properties:#过期日期:10800秒(3分钟)PitND.expire.pro=10800二、MainEventHERDMRedis.java:importorg.springframework.beans.facto......
  • C#中委托的使用
    一、简介简单记录一下在c#中,委托的使用方法二、委托2.1委托是什么?委托是一个类,可以将方法当作参数进行传递,保存对函数的引用。可以将委托看成执行方法的一个东西。2.......
  • 使用OpenMMLab系列的开源库时,常用的脚本合集。
    使用OpenMMLab系列的开源库时,常用的脚本合集。开源仓库:gy-7/mmlab_scripts脚本解释:anchor_visiual.py生成的锚框可视化aug_test.py自动数据增强,单文件可视化效果......
  • vue中Promise的使用方法详情
    vue中Promise的使用方法详情目录一、使用1.promise是一种异步解决方案2.asyncawait简介:promise是什么,它可以说是异步编程的一种解决方法,就拿传统的ajax发请求来说,单个......
  • vue3 使用element-plus 按需引入
    1:npminstallelement-plus--save2:组件按需引入所需插件:unplugin-auto-import、unplugin-vue-components图标按需引入所需插件:unplugin-auto-import、unplugin-......