springboot框架

1.什么是springboot框架

          Spring是一个开源框架,Spring是于2003 年兴起的一个轻量级的Java 开发框架,由Rod Johnson 在其著作《Expert One-On-One J2EE Development and Design》。Spring是为了解决企业级应用开发的复杂性而创建的,使用Spring可以让简单的JavaBean实现之前只有EJB才能完成的事情。但是Spring不仅仅局限于服务器端开发,任何Java应用都能在简单性、可测试性和松耦合性等方面从Spring中获益。
          总之springboot可以简化spring的搭建,并且快速创建一个spring的应用程序。该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置

2.springboot的特点

(1)可以创建独立的Spring应用程序,并且基于其Maven或Gradle插件,可以创建可执行的JARs和WARs;
(2)内嵌Tomcat或Jetty等Servlet容器;
(3)提供自动配置的“starter”项目对象模型(POMS)以简化Maven配置;
(4)尽可能自动配置Spring容器;
(5)提供准备好的特性,如指标、健康检查和外部化配置;
(6)绝对没有代码生成,不需要XML配置。

3.springboot工程的创建步骤

要求:
	1.JDK必须为1.8以上
	2.spring的jar必须5.0以上
	3.maven必须3.3以上

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

在这里插入图片描述
在这里插入图片描述
默认springboot扫描的包为主启动类所在的包以及子包。
写一个测试
在这里插入图片描述

@RestController
public class Controller {

    @GetMapping("hello")
    public Map<String,Object> hello(){
        Map<String,Object> map = new HashMap<>();
        map.put("name","zs");
        map.put("age",18);
        return map;
    }
}

运行程序
在这里插入图片描述
项目创建成功

4.springboot的配置文件

第一种: properties属性文件

	# 修改springboot中tomcat端口号.
	server.port=8888

第二种:  yml文件
	server:
	port: 6666

不管是哪种,他们的名字必须以application开始。
如果两个配置文件同时存在,而且有些内容一样。按照properties的优先级高。
如果有些不一样,两个配置文件不一样的会合并在一起。

语法:
在这里插入图片描述

1,如果配置是写在properties里面,只有Map不能取到

2,如果配置写在yml 数组  集合  都取不到

3,如果属性是使用驼峰命名法则不能使用属性名注入,要使用@Value("${student.user-name}")来取值

不能使用@Value("${student.userName}")来取值

读取springboot配置文件中的内容

在application.properties中写入

student.name=zs
student.age=18
student.hobby[0]=sing
student.hobby[1]=swimming
student.map.clazz=qy151
student.map.stuId=120

创建实体类 将读取application.properties配置文件中的值并赋值给Student类中的属性

@Data
@Component //该类对象的创建和销毁都有spring容器来管理
@ConfigurationProperties(prefix = "student") //读取springboot中的配置内容,读取以前缀为student
public class Student {
    String name;
    String age;
    String[] hobby;
    Map<String,Object> map;
}
	@Autowired //spring容器自动注入该对象
    Student student;
    @GetMapping("/getStu")
    public Student getStu(){
        System.out.println(stuName);

        return student;
    }

在这里插入图片描述
读取application.yml配置文件中的值并赋值给Student类中的属性

server:
  port: 8082

student:
  name: zs
  age: 18
  hobby:
    - sing
    - dance
    - rap
    - basketball
  map:
    clazz: qy151
    stuI

在这里插入图片描述
@Value 只能放在我们的类属性上。而且它只能读取基本类型和字符串类型。
在这里插入图片描述

5.springboot的 profiles配置

在开发中,一般有三种环境
    1. 生产环境  [项目上线,客户在使用中]
    2. 开发环境
    3. 测试环境
有时候开发环境和生产环境的配置方法是不一样的,那么如何快速的切换呢,这里就要使用profiles文件

在这里插入图片描述

1.创建applicatin-dev.properties
	server.port=8081
2.创建applicatin-online.properties
	server.port=8082	
3.创建applicatin-test.properties
	server.port=8083
4.修改application.properties
	spring.profiles.active=developer
5. 测试
6.总结 在application.properteis里面激活哪个文件就会使用哪个端口

6.springboot注册web三大组件

web的三个组件:
	Servlet和Filter以及Linstener监听器。

早期注册web三大组件:
(1)注册Servlet

1.注册Servlet类
2.注册到Tomcat容器web.xml
<servlet>
	<servlet-name></servlet-name>
	<servlet-class>Servlet类</servlet-class>
</servlet>
<servlet-mapping>
	<servlet-name></servlet-name>
	</url-parterrn>/</url-parterrn>
</servlet-mapping>
public class MyServlet extends HttpServlet{
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("===helloServlet===");
    }
}
@Configuration//该类为配置类 xml文件
public class ServletConfig {

    @Bean //理解为配置文件中的bean
    public ServletRegistrationBean<Servlet> registrationBean(){
        //创建一个Servlet注册器
        ServletRegistrationBean<Servlet> registrationBean = new ServletRegistrationBean<>();
        registrationBean.setName("my");
        registrationBean.setServlet(new MyServlet());
        registrationBean.addUrlMappings("/my");
        return registrationBean;
    }
}

(2)注册filter

public class MyFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("=====filter=====");
        filterChain.doFilter(servletRequest,servletResponse);
    }
}
 @Bean
    public FilterRegistrationBean<Filter> filterRegistrationBean(){
        FilterRegistrationBean<Filter> filterRegistrationBean=new FilterRegistrationBean<>();
        filterRegistrationBean.setName("myfilter");
        filterRegistrationBean.setFilter(new MyFilter());
        filterRegistrationBean.addUrlPatterns("/*");
        return filterRegistrationBean;
    }

7.springboot自动装配

自动装配在SpringBoot是基于EnableAutoConfiguration来实现的
springboot的自动装配启动类上的注解@SpringBootApplication有关
按Ctrl+点进去可以看到@SpringBootApplication相关信息

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration  //继承自@Configuration,二者功能一致,标注当前类是配置类
@EnableAutoConfiguration 
@ComponentScan(
excludeFilters = {@Filter(
type = FilterType.CUSTOM,
classes = {TypeExcludeFilter.class}
), @Filter(
type = FilterType.CUSTOM,
classes = {AutoConfigurationExcludeFilter.class}
)}

1.  @SpringBootConfiguration  :继承自@Configuration,二者功能一致,标注当前类是配置类	
2.  @ComponentScan用于类或接口上主要是指定扫描路径,跟Xml里面的<context:component-scan base-	package="" />配置一样。springboot如果不写这个扫描路径的话,默认就是启动类的路径。
3.  @EnableAutoConfiguration 注解表示启动自动装配 其中的注解包括
			@Target({ElementType.TYPE})
			@Retention(RetentionPolicy.RUNTIME)
			@Documented
			@Inherited
			@AutoConfigurationPackage
			@Import({AutoConfigurationImportSelector.class})
			public @interface EnableAutoConfiguration
	其中装配原理与注解@Import({AutoConfigurationImportSelector.class})有关
	这个注解重点是AutoConfigurationImportSelector这个类getCandidateConfigurations方法
	这个方法里面通过SpringFactoriesLoader.loadFactoryNames()
	扫描所有具有META-INF/spring.factories的jar包
spring-boot-autoconfigure-x.x.x.x.jar里就有一个spring.factories文件。spring.factories文件由一组一组的Key = value的形式,其中一个key是EnableAutoConfiguration类的全类名,而它的value是一个以AutoConfiguration结尾的类名的列表,有redis、mq等这些类名以逗号分隔。

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
getAutoConfigurationEntry这个方法当执行完getCandidateConfigurations这个方法的时候我们可以看到此时总共加载了131个自动配置类。原本127因为我自己加了一些jar包所以加载进去

8. springboot整合数据源

8.1 集成默认数据源

数据源即数据库中的数据,也就是springboot连接数据库
(1)导入依赖

	 <!--加入数据源的启动依赖: springboot启动时会加载对应的自动装配类。-->
        <dependency>
            <groupId>repMaven.org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
            <version>2.6.7</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

(2)配置数据源信息—application.properties

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.url=jdbc:mysql://localhost:3306/mydb?serverTimezone=Asia/Shanghai

(3)单元测试

@SpringBootTest
class WxApplicationTests {

    @Autowired
    private DataSource dataSource;

    @Test
    void contextLoads() throws SQLException {
        System.out.println(dataSource.getConnection());
    }
}

在这里插入图片描述
上面默认这个数据源使用的连接池Hikari。如果不想使用默认的连接池,我们可以引入第三方的连接池。如druid

8.2 集成druid数据源

(1)引入依赖

	   <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.2.8</version>
        </dependency>

(2)配置文件

spring.datasource.druid.url=jdbc:mysql://localhost:3306/mydb?serverTimezone=Asia/Shanghai
spring.datasource.druid.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.druid.username=root
spring.datasource.druid.password=root
#初始化的个数
spring.datasource.druid.initial-size=5
# 最大活跃数
spring.datasource.druid.max-active=10
# 最大等待时间
spring.datasource.druid.max-wait=3000
# 最小的闲置个数
spring.datasource.druid.min-idle=5

(3)测试

 @Test
    void test01() {
        System.out.println(dataSource);
    }

在这里插入图片描述

9. springboot整合mybatis

(1)引入依赖

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

(2)修改配置文件

#指定映射文件的路径
mybatis.mapper-locations=classpath:mapper/*.xml

在resources文件下创建mapper文件

(3)创建数据
         随便连接数据库中存在的表

	(1)创建实体类(2)在dao层中写一个简单得查询接口 (3)在mapper层中写查询语句
@Data
public class Dept {
    private Integer id;
    private String name;
    private String address;
}
@Repository
public interface DeptMapper {
    public Dept findById(Integer id);
    
}
<?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.wx.dao.DeptMapper">
    <select id="findById" resultType="com.wx.entity.Dept">
        select * from tb_dept where id=#{id}
    </select>
</mapper>

(4)在主启动类上加入注解

@SpringBootApplication
@MapperScan(basePackages = "com.wx.dao") //为指定包下的接口生成代理实现类
public class WxApplication {

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

}

(5) 测试

 @Test
    void test02() {
        System.out.println(deptMapper.findById(2));
    }

在这里插入图片描述

10. springboot整合PageHelper分页插件

(1)引入依赖

		<dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
            <version>1.4.2</version>
        </dependency>

(2)配置数据

@Repository
public interface DeptMapper {
    public Dept findById(Integer id);
    public List<Dept> findAll();
}

	<select id="findAll" resultType="com.wx.entity.Dept">
        select * from tb_dept
    </select>

(3)测试

    @Test
    void test03() {
        PageHelper.startPage(1,5);
        List<Dept> list = deptMapper.findAll();
        PageInfo<Dept> pageInfo = new PageInfo<>(list);
        System.out.println(pageInfo);
    }

在这里插入图片描述

11.springboot整合swagger2.

编写和维护接口文档是每个程序员的职责,根据Swagger2可以快速帮助我们编写最新的API接口文档,再也不用担心开会前仍忙于整理各种资料了,间接提升了团队开发的沟通效率。

 swagger通过注解表明该接口会生成文档,包括接口名、请求方法、参数、返回信息的等等。
 	@Api:修饰整个类,描述Controller的作用
	@ApiOperation:描述一个类的一个方法,或者说一个接口
	@ApiParam:单个参数描述
	@ApiModel:用对象来接收参数
	@ApiModelProperty:用对象接收参数时,描述对象的一个字段
	@ApiImplicitParam:一个请求参数
	@ApiImplicitParams:多个请求参数

操作步骤:
(1)引入依赖

引入依赖注意版本要和springboot的版本适配 不能太高 否则会报错

	<dependency>
            <groupId>com.spring4all</groupId>
            <artifactId>swagger-spring-boot-starter</artifactId>
            <version>1.9.1.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>com.github.xiaoymin</groupId>
            <artifactId>swagger-bootstrap-ui</artifactId>
            <version>1.7.8</version>
        </dependency>

(2)创建swagger配置类

@Configuration
public class SwagerConfig {

    @Bean
    public Docket docket(){
        Docket docket = new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())//设置api文档信息
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.wx.controller")) //指定为哪些包下的类生成接口文档。
                .build();

        return docket;
    }

    //定义自己接口文档信息
    private ApiInfo apiInfo() {
        Contact DEFAULT_CONTACT = new Contact("wx", "http://www.wx.com", "110@qq.com");
        ApiInfo apiInfo = new ApiInfo("部门在线文档", "对部门的增删改查", "V1.0", "http://www.dept.com",
                DEFAULT_CONTACT, "XX科技", "http://www.xx.com", new ArrayList<VendorExtension>());

        return apiInfo;
    }
}

(3)在主启动类中开启swagger注解

@SpringBootApplication
@MapperScan(basePackages = "com.wx.dao") //为指定包下的接口生成代理实现类
@EnableSwagger2 //开启swagger注解
public class WxApplication {

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

}

(4)在controller层写自己的业务需求
(5)测试

在这里插入图片描述

  • 6
    点赞
  • 66
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值