SpringBoot简单使用(2)

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 测试。数据添加成功

posted @ 2022-09-01 21:28  Sunward阳  阅读(56)  评论(0)    收藏  举报