栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Springboot学习记录

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Springboot学习记录

SpringBoot:

 自动配置pom.xml文件:
    spring-boot-dependencies:核心在父工程中,在引入一些springboot依赖的时候,不需要指定版本
    springboot启动器依赖:
    
                org.springframework.boot
                spring-boot-starter
    
   @Bean:把对象注入到spring容器中,相当于标签
             @Bean(name="容器中的名称") 不指定默认是方法名字为id

   @Value("${key}"): 获取值

主程序:

    @SpringBootApplication:标注这个类是一个springboot的应用
     复合注解:
     @SpringBootConfiguration:作为配置文件使用,可以用@bean声明对象注入容器
             @Configuration:spring的配置类
                 @Component:spring的组件
     @EnableAutoConfiguration:启动自动配置
             @AutoConfigurationPackage:自动配置包
                 @Import(AutoConfigurationPackages.Registrar.class):自动配置包注册
     @ComponentScan:扫描器,找到注解 默认扫描所在的类的包和子包,所以要放同级目录

   @Import(AutoConfigurationImportSelector.class):自动配置导入选择类
            getAutoConfigurationEntry:获得自动配置的实体的方法
            getCandidateConfigurations:获得候选的配置的方法
                    标注了EnableAutoConfiguration的注解的类
                    protected Class getSpringFactoriesLoaderFactoryClass() {
                            return EnableAutoConfiguration.class;
                        }

 获取所有的加载配置
            public static List loadFactoryNames(Class factoryType, @Nullable ClassLoader classLoader) {
                    ClassLoader classLoaderToUse = classLoader;
                    if (classLoader == null) {
                        classLoaderToUse = SpringFactoriesLoader.class.getClassLoader();
                    }
                    String factoryTypeName = factoryType.getName();
                    return (List)loadSpringFactories(classLoaderToUse).getOrDefault(factoryTypeName, Collections.emptyList());
                }

 loadSpringFactories()方法
                 Enumeration urls = classLoader.getResources("META-INF/spring.factories");:获取配置

@ConditionalOnClass注解判断导入条件是否满足

   @ConfigurationProperties(perfix = "变量名前缀"):可以在yaml配置文件中绑定实体类并在配置文件中赋值

@PropertySource(value = "application.yaml"):加载指定配置文件

Springboot注解的结论:

Springboot在启动的时候从spring-boot-autoconfigure-2.6.7.jar/METE-INF/spring.factories中获取EnableAutoConfiguration的值
将这些值作为自动配置类导入容器,满足条件后自动配置类就进行自动配置工作

Springboot应用启动的结论:

SpringApplication.run(Application.class, args):SpringApplication类
run方法
1.推断应用的类型是普通项目还是WEB项目
2.0查找并加载所有可用初始化器,设置到initializers属性中
3.找出所有的应用程序监听器,设置到listeners属性中
4.推断并设置main方法的定义类,找到运行的主类

Springboot自动装配的结论:

1.Springboot启动会加载大量自动配置类(xxxAutoConfigurartion类)
2.我们需要的组件功能要在springboot默认写好的自动配置类中
3.给容器中自动配置类添加组件时,会从xxxProperties类中获取属性,我们只需要在application配置文件中指定这些属性的值

Springboot配置文件application.properties(yaml):

JSR303校验:
@NotNull 注解元素必须是⾮空
@Null 注解元素必须是空
@Digits 验证数字构成是否合法
@Future 验证是否在当前系统时间之后
@Past 验证是否在当前系统时间之前
@Max 验证值是否⼩于等于最⼤指定整数值
@Min 验证值是否⼤于等于最⼩指定整数值
@Pattern 验证字符串是否匹配指定的正则表达式
@Size 验证元素⼤⼩是否在指定范围内
@NotNull 注解元素必须是⾮空
@Null 注解元素必须是空
@Digits 验证数字构成是否合法
@Future 验证是否在当前系统时间之后
@Past 验证是否在当前系统时间之前
@Max 验证值是否⼩于等于最⼤指定整数值
@Min 验证值是否⼤于等于最⼩指定整数值
@Pattern 验证字符串是否匹配指定的正则表达式
@Size 验证元素⼤⼩是否在指定范围内

Springboot使用以下方式处理静态资源:

webjars localhost:8080/webjars/
public、static、/**、resources localhost:8080/
优先级:resources>static(默认)>public
templates目录下的文件需要导入thymeleaf依赖才可以访问(springboot2.7版本好像可以不用导入)

实现ComnandLineRunner接口和ApplicationRunner接口:

两个接口都有一个run方法,执行时间在容器对象创建好后自动执行run方法
可以完成自定义在容器对象创建好的一些操作

Springboot集成Jsp:

 1.加入处理jsp的依赖,负责编译jsp
     
            
                javax.servlet
                javax.servlet-api
            
            
            
                javax.servlet
                jstl
            
            
            
                org.springframework.boot
                spring-boot-starter-tomcat
            
            
            
                org.apache.tomcat.embed
                tomcat-embed-jasper
            
      2.创建一个放jsp的目录,webapp
      3.需要在pom文件指定jsp文件编译后的存放目录
      
            
                
                src/main/webapp
                
                META-INF/resources
                
                
                    (XX/X.X)
                
            
      
      4.创建Controller,访问jsp
      @Controller
      public class IndexController {
          @RequestMapping("/index")
          public String index(Model model){
              model.addAttribute("data","SpringbootJsp");
              return "index";
          }
      }
      5.在springboot配置文件配置视图解析器
      #配置视图解析器
      spring:
        mvc:
          view:
            prefix: /WEB-INF/
            suffix: .jsp

Springboot集成拦截器:

 实现拦截器接口
    public class LoginInterceptor implements HandlerInterceptor {
        @Override
        ppublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
                 if (request.getSession().getAttribute(Contants.SESSION_USER)==null){
                     //重定向到index页面
                     response.sendRedirect(request.getContextPath()+"/settings/qx/user/index.do");
                     return false;
                 }
                 return true;
             }
    }
    @Configuration
    public class MyConfig implements WebMvcConfigurer {
        //添加拦截器对象,注入容器中
        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            HandlerInterceptor handlerInterceptor = new LoginInterceptor();
            //指定拦截的请求url地址
            String path [] = {"/user/**"};
            //指定不拦截的请求地址
            String excludepath [] = {"/user/login"};
            registry.addInterceptor(handlerInterceptor).addPathPatterns(path).excludePathPatterns(excludepath);
        }
    }

Springboot集成servlet:

 自定义一个类继承HttpServlet:
    public class MyServlet extends HttpServlet {
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            //get请求调用post请求
            doPost(req, resp);
        }
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            resp.setContentType("text/html;charset=utf-8");
            PrintWriter out  = resp.getWriter();
            out.println("Servlet");
            out.flush();
            out.close();
        }
    }
    注册servlet到bean工厂:
    @Configuration
    public class WebApplicationConfig {
        //定义方法,注册servlet对象
        @Bean
        public ServletRegistrationBean servletRegistrationBean(){
            //两个参数一个是servlet对象,一个是url地址
            ServletRegistrationBean bean = new ServletRegistrationBean(new MyServlet(),"/myservlet");
            return bean;
        }
    }

Springboot集成Filter过滤器:

1.自定义过滤器:
    public class MyFilter implements Filter {
        @Override
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
            System.out.println("执行了dofilter方法");
            filterChain.doFilter(servletRequest,servletResponse);
        }
    }
    2.注册过滤器对象:
     @Bean
        public FilterRegistrationBean filterRegistrationBean(){
            FilterRegistrationBean bean = new FilterRegistrationBean();
            bean.setFilter(new MyFilter());
            bean.addUrlPatterns("/user/*");
            return bean;
        }

Springboot集成Mybatis:

1.加入Mybatis依赖和Mysql驱动依赖

    org.mybatis.spring.boot
    mybatis-spring-boot-starter
    2.2.2



    mysql
    mysql-connector-java
    runtime

2.pom.xml指定把src/main/java目录的xml文件包含classpath中
 
        
            
                src/main/java
                
                    *.xml
                
            
        
3.创建实体类对象
4.创建Mapper接口,创建查询方法
@MapperScan(basePackages = "com.springboot.mapper"):入口程序用这个注解mapper接口上面可以不用写@Mapper注解
@Mapper
public interface UserMapper {

	User selectByid(@Param("user_id") String user_id);
}
5.创建Mapper接口对应的xml文件,编写sql语句
 



6.创建service层接口和实现类,调用mapper的方法,完成数据库操作
service层接口:
public interface UserService {
    User queryUser(String user_id);
}
实现类:
@Service
public class UserServiceImpl implements UserService {
    @Resource
    private UserMapper userMapper;
    @Override
    public User queryUser(String user_id) {
        return userMapper.selectByid(user_id);
    }
}
7.创建Controller对象访问service层
@Controller
public class UserController {
    @Resource
    private UserService userService;
    @RequestMapping("/user/query")
    @ResponseBody
    public String queryUser(String user_id){
        User user = userService.queryUser(user_id);
        return user.toString();
    }
}
8.写application配置文件(配置数据库连接信息)
#链接数据库
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/ssmuser?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=root
#开启日志
mybatis:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

Mybatis逆向工程插件

   
     
             org.mybatis.generator
             mybatis-generator-maven-plugin
             1.3.6
             
                 
                 GeneratorMapper.xml
                 true
                 true
             
     

Springboot开启事务:

在入口类使用注解@EnableTransactionManagement
在访问数据库的Service层方法上添加注解@Transactional

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/940996.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号