springboot 快速使用

  • Post author:
  • Post category:其他



目录


对于SSM有基础的适用


springboot默认扫描策略是@SpringBootApplication注解所在包及其子包。


全局初始化懒加载


部分bean懒加载初始化,在bean上加@Lazy注解。


导入外部数据


为外部文件指定别名


属性自动配置,使用@ConfigurationProperties注解【要求在application.yml或者application.properties中】


自动注入属性的验证 @ConfigurationProperties Validation


springMVC自动配置


完全接管springMVC,【不推荐】


静态资源位置:


欢迎页面默认index.html


自定义error pages。


springboot整合mybatis。【纯注解注解】


application.yml中配置文件书写


dao接口:


实体类:


service


测试代码:


结果:


整合mybatis细节:



对于SSM有基础的适用

springboot 应用目录简介:


配置文件是application.yaml


springboot默认扫描策略是@SpringBootApplication注解所在包及其子包。

全局初始化懒加载

spring:
  main:
    lazy-initialization: true

部分bean懒加载初始化,在bean上加@Lazy注解。

导入外部数据

spring:
  config:
    import: classpath:init.properties

为外部文件指定别名

#指定名称
config:
  activate:
    on-profile: dev
#    激活
spring:
  profiles:
    active: dev

属性自动配置,使用@ConfigurationProperties注解【要求在application.yml或者application.properties中】

类似于spring的@PropertySource+@Value

@Component
@ConfigurationProperties("person")
public class Person {
    private Integer id;
    private String name;
}

一般使用自动属性注入是使用setter注入。要使用构造注入:

@ConfigurationProperties("person")
public class Person {
    private Integer id;
    private String name;
//@ConstructorBinding 会报错
    public Person() {
    }
//    指定构造使用的方法
    @ConstructorBinding
    public Person(Integer id, String name) {
        this.id = id;
        this.name = name;
        System.out.println("constructor");
    }
@Configuration
@EnableConfigurationProperties(Person.class)
public class MyConfig  {
}

或者

@Configuration
//@EnableConfigurationProperties(Person.class)
//指定配置属性扫描包,包下必须有@ConfigurationProperties注解,并同时会把其加入IOC容器中
@ConfigurationPropertiesScan(basePackages = {"boot"})
public class MyConfig  {
}

自动注入属性的验证 @ConfigurationProperties Validation

用jsr303。导入javax.valdiation外部依赖验证。就是对于邮箱,全是数字等一些正则验证注解化。

springMVC自动配置

springMVC直接写controller层即可,常用的字符编码拦截器,视图解析器等,springboot已经帮我们自动配好了。

springboot推荐模板引擎thymeleaf【注意,不是JSP】

   <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>

默认前缀是“/resources/templates”,后缀是“.html”。

增加MVC的额外功能,增加拦截器,格式化器,视图控制器和其他特性,新建配置类@Configuration,实现WebMvcConfigurer接口【推荐】

@Configuration
//这是一个MVC扩展配置
public class MyConfig  implements WebMvcConfigurer{
}

完全接管springMVC,【不推荐】

增加@EnableWebMvc注解,在类上。

静态资源位置:

一般在resources/static目录下,

#    表示static目录下的多级目录
  mvc:
    static-path-pattern: "/resources/static/**"

欢迎页面默认index.html

自定义error pages。

src/
 +- main/
     +- java/
     |   + <source code>
     +- resources/
         +- static/
             +- error/
             |   +- 404.html
             +- <other public assets>

为了适应更复杂的映射关系,可实现ErrorViewResolver接口。

@Controller
public class MistakeHandle implements ErrorViewResolver {
    @Override
    public ModelAndView resolveErrorView(HttpServletRequest request, HttpStatus status, Map<String, Object> model) {
        return null;
    }
}

springboot整合mybatis。【纯注解注解】

依赖:

 <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.3</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
<dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.4</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>

此时,默认的数据源是springboot默认提供的HikariCP。

application.yml中配置文件书写

spring:
#  数据源配置
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: "jdbc:mysql://localhost:3306/demo"
    username: root
    password: 1234
mybatis:
#  起别名
  type-aliases-package: com.ex.demo.entity

dao接口:

package com.ex.demo.dao;

import com.ex.demo.entity.Person;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
//启动类中写@MapperScan注解,否在在此写@Mapper注解

@Transactional
public interface IPersonDao {
    @Select("select * from users")
    public List<Person> findAll();

    @Insert("insert into users(name) values(#{name}) ")
    public boolean add(Person per);
}

实体类:

package com.ex.demo.entity;

public class Person {
    private Integer id;
    private String name;

    public Person() {
    }

    public Integer getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

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

service

package com.ex.demo.service;

import com.ex.demo.dao.IPersonDao;
import com.ex.demo.entity.Person;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class PersonService {
    @Autowired
    private IPersonDao personDao;

    public List<Person> searchAll(){
        List<Person> ret = null;
        ret = personDao.findAll();
        return  ret;
    }
//此注解表示开启事务
    @Transactional
    public boolean addPerson(Person per)throws RuntimeException{
        boolean ret = false ;
        ret = personDao.add(per);

        return  ret;
    }
}

测试代码:

package com.ex.demo;

        import com.ex.demo.dao.IPersonDao;
        import com.ex.demo.entity.Person;
        import com.ex.demo.service.PersonService;
        import org.springframework.beans.factory.annotation.Autowired;
        import org.springframework.boot.test.context.SpringBootTest;

        import java.util.List;

@SpringBootTest
public class Test {
    @Autowired
    private PersonService personService;

    @org.junit.jupiter.api.Test
    public void test1(){
     Person per = new Person();
     per.setName("farest2");

     System.out.println(personService.addPerson(per));

    }
    @org.junit.jupiter.api.Test
    public void test2(){
        List<Person>all = personService.searchAll();
        for (Person person : all) {
            System.out.println(person);
        }
    }
}

结果:

idea静态编译的时候会报错,但是事实上没问题。

这就是springboot整合持久层的代码。

整合mybatis细节:

增删改操作 @Transational
查询操作     @Transational(propagation = propagation.supports,readonly=true)

在spring中,mybatis加事务需要在数据源(DataSource)上加@EnableTransactionManagement注解,由于springboot的属性自动配置,所以,我们不需要再加这个注解了,只需要加@Transactional注解即可。



版权声明:本文为weixin_46083389原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。