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

SpringBoot笔记01 XML和JavaConfig,SpringBoot入门

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

SpringBoot笔记01 XML和JavaConfig,SpringBoot入门

简介 为什么要使用SpringBoot

因为Spring,SpringMVC需要使用大量的配置文件(xml文件)

还需要配置各种对象,把使用的对象放入到spring容器中才能使用对象

需要了解其他框架配置规则

SpringBoot就相当于 不需要配置文件的Spring+SpringMVC,常用框架和第三方库都已经配置好了,拿来就可以使用。

SpringBoot开发效率高,使用方便很多。

XML和JavaConfig

Spring使用Xml作为容器配置文件,在3.0以后加入了JavaConfig,使用java类做配置文件使用

什么是JavaConfig

JavaConfig:是Spring提供的使用java类配置容器,配置SpringIOC容器的纯Java方式。在这个Java类中可以创建Java对象,把对象放入spring容器中(注入到容器中)

使用两个注解:

@Configuration:放在一个类的上面,表示这个类是作为配置文件使用的。

@Bean:声明对象,把对象注入到容器中

优点:

可以使用面向对象的方式,一个配置类可以继承配置类,可以重写方法

避免繁琐的xml配置

Xml配置容器 准备工作

新建空工程

创建模块(Maven)

导入依赖

    
        
            org.springframework
            spring-context
            5.3.1
        
        
            junit
            junit
            4.12
            test
        
    

    
        
            
            
                org.apache.maven.plugins
                maven-compiler-plugin
                3.5.1
                
                
                    1.8
                    1.8
                    
                    UTF-8
                
            
        
    

 创建Student类

public class student {
    private String name;
    private Integer age;
    private String sex;

    public String getName() {
        return name;
    }

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

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    @Override
    public String toString() {
        return "student{" +
                "name='" + name + ''' +
                ", age=" + age +
                ", sex='" + sex + ''' +
                '}';
    }
}
配置

在resources下创建配置文件beans.xml




    
        
        
        
    
    
测试
    
    @Test
    public void test01() {
        String config = "beans.xml";
        ApplicationContext context = new ClassPathXmlApplicationContext(config);
        Student student = context.getBean("myStudent", Student.class);
        System.out.println("容器中的对象:" + student);
    }
JavaConfig配置容器 新建SpringConfig类
//该注解表示当前类作为配置文件使用,就是用来配置容器的
@Configuration
public class SpringConfig {

    
    @Bean(name = "myStudent")
    public Student createStudent() {
        Student student = new Student();
        student.setName("GYQ");
        student.setAge(18);
        student.setSex("男");
        return student;
    }
}
测试
    
    @Test
    public void test02() {
        ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
//        Student student = context.getBean("createStudent", Student.class);
        Student student = context.getBean("myStudent", Student.class);
        System.out.println("使用JavaConfig创建的bean对象:" + student);
    }
@ImportResource

用于导入其他的xml配置文件,等同于xml文件的resources

准备工作

创建数据类

public class Cat {
    private String cardId;
    private String name;
    private Integer age;

    public String getCardId() {
        return cardId;
    }

    public void setCardId(String cardId) {
        this.cardId = cardId;
    }

    public String getName() {
        return name;
    }

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

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Cat{" +
                "cardId='" + cardId + ''' +
                ", name='" + name + ''' +
                ", age=" + age +
                '}';
    }
}

在applicationContext.xml配置文件中配置



    
        
        
        
    
使用注解引入配置文件

注意这里的value和location意义相同,其值为一个数组,多个值时用法如下

@Configuration
@ImportResource(value = {"classpath:applicationContext.xml", "classpath:beans.xml"})
public class SpringConfig {
}
测试
    
    @Test
    public void test03() {
        ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
        Cat cat = context.getBean("myCat", Cat.class);
        System.out.println("cat==" + cat);
    }
@PropertyResource

用于读取属性配置文件,使用属性配置文件可以实现外部化配置,在程序代码之外提供数据

创建config.properties

在resource目录下

创建数据类Tiger
@Component("tiger")
public class Tiger {
    @Value("${tiger.name}")
    private String name;
    @Value("${tiger.age}")
    private Integer age;

    @Override
    public String toString() {
        return "Tiger{" +
                "name='" + name + ''' +
                ", age=" + age +
                '}';
    }
}
在配置类中配置

测试
    
    @Test
    public void test04() {
        ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
        Tiger tiger = context.getBean("tiger", Tiger.class);
        System.out.println("tiger==" + tiger);
    }

注意:如果出现乱码问题在设置中进行修改

Spring Boot入门

SpringBoot是Spring中的一个成员,可以简化Spring,SpringMVC的使用,他的核心还是IOC容器

特点

创建SpringBoot项目 Spring Initializr

使用Spring Boot提供的初始化器创建

选择依赖项

查看创建的Spring项目的结构

static:静态资源(js,css,图片...)

templates:模板文件

application.properties:SpringBoot重要的配置文件


查看pom.xml

    
    
        org.springframework.boot
        spring-boot-starter-parent
        2.4.2
         
    

    
    com.gyq.boot
    test02-springboot
    0.0.1-SNAPSHOT
    test02-springboot
    test02-springboot

引入了spring-boot-starter-web依赖,他会引入web场景所需的依赖

注意:由于初始化器的地址是国外的,比较慢,很容易访问失败

我们可以将它替换成国内的

也可以在浏览器使用

直接创建Maven项目

在pom.xml中添加依赖


    
        org.springframework.boot
        spring-boot-starter-parent
        2.4.2
         
    

    
        
            org.springframework.boot
            spring-boot-starter-web
        
    

在resources下新建

创建主程序类

编写controller

测试

Spring Boot注解 @SpringBootApplication

使用在主启动类上,通过它的main方法启动应用

@SpringBootApplication是一个复合注解。它由以下三个注解构成

@SpringBootConfiguration:代表标识的类当作配置文件使用

在配置类中向容器中注入对象


@EnableAutoConfiguration:启用自动配置

把Java对象配置好,注入到容器中,例如可以把mybatis的对象创建好,放入到容器中。


@ComponentScan:开启组件扫描

默认扫描当前配置类所在包及其子包。

Spring Boot配置文件 application.扩展名

两种扩展名:properties(k=v);yml(k:空格v)

properties

#设置端口号
server.port=8081
#设置访问应用的上下文路径
server.servlet.context-path=/springboot

yml

yml是一种yaml格式的配置文件,注意采用一定的空格,换行等格式排版进行配置。

yaml是一种直观的能够被计算机识别的数组序列化格式,容易被人阅读,yaml类似于xml,但是语法比它简洁的多,值与前面的冒号配置项必须有一个空格

server:
  port: 8080
  servlet:
    context-path: /myboot

当两种格式同时存在默认使用的是properties格式,推荐使用yml格式

多环境配置

在实际开发过程中,我们的项目会经历很多的阶段(开发->测试->上线),每个阶段的配置也会不同,例如:端口,上下文根,数据库等,那么这个时候为了方便在不同的环境之间切换,SpringBoot提供了多环境配置,具体步骤如下。

1、为每个环境创建一个配置文件,命名必须以application-环境标识.properties/yml

dev:开发环境        test:测试环境        product:生产环境

2、在application.yml中激活所需配置文件

#激活指定配置文件
spring:
  profiles:
    active: dev
自定义配置

SpringBoot的核心配置文件中,除了使用内置的配置项之外,我们还可以再自定义配置,然后采用如下注解去读取配置的属性值

现在application.yml中自定义key: value

server:
  port: 8080
  servlet:
    context-path: /myboot


#自定义key-value
person:
  name: GYQ
  age: 18

@Value注解

@ConfigurationProperties

将整个文件映射成一个对象,用于自定义配置项比较多的情况

在config包下新建PersonInfo类

测试

也可以添加依赖项,处理有关元数据

        
            org.springframework.boot
            spring-boot-configuration-processor
            true
        
Spring Boot使用JSP

框架不支持JSP,需要一些配置才能使用。不推荐

加入一个处理jsp的依赖,负责编译jsp文件

        
            org.apache.tomcat.embed
            tomcat-embed-jasper
        

如果需要使用servlet,jsp,jstl的功能

        
            javax.servlet.jsp
            javax.servlet.jsp-api
            2.3.1
        
        
            javax.servlet
            javax.servlet-api
        
        
            jstl
            jstl
        

创建一个存放jsp的目录,一般叫做webapp

需要在pom.xml指定jsp文件编译后存放的目录,META-INF/resources


        
        
            
                
                src/main/webapp
                
                META-INF/resources
                
                
                    **/*.*
                
            
        

创建Controller,访问jsp

在springboot配置文件中配置视图解析器

spring:
  mvc:
    view:
      prefix: /
      suffix: .jsp
Spring Boot使用ApplicationContext

在main方法中SpringApplication.run()方法获取返回的Spring容器对象,在获取业务bean进行调用

CommandLineRunner接口

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

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

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

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