SpringBoot学习

2021/6/28 23:25:58

本文主要是介绍SpringBoot学习,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

spring缺点

1.配置繁琐

2.依赖繁琐

springboot提供了一种快速开发spring项目的方式,而不是对spring功能上的加强。

springboot在创建项目时,使用jar的打包方式。

springboot的引导类,是相距入口,运行main方法就可以启动项目。

同一级目录下配置文件先后顺序

application.properties >application.yml>application.yaml

springboot读取配置内容

1.@value

2.Environment 

3.@ConfigurationProperties

1.@value

1.在properties文件中如下示:

name=abc

@value获取值

接着,在类中可以通过@Value获取对应内容并赋值。

@Value("${name}")
private  String name;

2.Environment

@Autowired
Environment environment;

类中可以通过

System.out.println(environment.getProperty("person.name"));

3.ConfigurationProperties获取配置类

#对象行内写法
person: {name: kobe,age: 18}
@Component
@ConfigurationProperties(prefix = "person")
public class Person {
    private String name;
    private Integer age;

    public Person() {
    }

    public Person(String name, Integer age) {
        this.name = name;
        this.age = age;
    }

    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 "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
@Autowired
Person person;
@GetMapping("/hello")
public String hello(){
    System.out.println(person);
    return "hello springboot demo";
}

Springboot配置

profile

我们在开发springboot应用时,通常一套程序会被安装到不同环境中,比如:开发、测试、生产等。其中数据库地址、服务器端口等等配置都不同。如果每次打包时,都要修改配置文件,那么非常麻烦。profile功能就是进行动态配置切换。

1)profile配置方式

1.多profile文件方式

2.yml多文件方式(---分割不同配置)

---
server:
  port: 8181
spring:
  profiles: dev
---
server:
  port: 8282
spring:
  profiles: test
---
server:
  port: 8383
spring:
  profiles: pro
---
spring:
  profiles:
    active: dev

2)profile激活方式

1.配置文件(如上)

spring.profiles.active=dev    #激活

2.虚拟机参数

-Dspring.profiles.active=pro

3.命令行参数

--spring.profiles.active=pro

生产中配置环境profile切换

java  -jar  xxxxx.jar  --spring.profiles.active=pro

springboot内部配置加载顺序

springboot启动时,会从以下位置加载配置文件:

1.file:/config/:当前项目下的/config目录下

2.file:/          :当前项目根目录

3.classpath:/config/:classpath的config目录

4.classpath:/  :classpath的根目录

加载顺序为上文的排列顺序,高优先级配置的属性会生效。

classpath:/config/:classpath的config目录------classpath:/  :classpath的根目录比较

file:/config/:当前项目下的/config目录下----------file:/ :当前项目根目录比较

修改项目的访问路(刚开始http://localhost:9191/hello访问控制层,后面http://localhost:9191/hello/hello)

#修改项目的访问路径默认为/
server.servlet.context-path=/hello

生产指定端口springboot加载外部文件

1.

2.

3.

springboot整合Junit

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

springboot整合myBatis

1.没有映射文件

2.mapper.xml

application.yml配置文件

#Mapper映射文件路径
mybatis:
  mapper-location: classpath:mapper/*Mapper.xml
  type-aliases-package: com.etc.entity #别名,不然要指定详细实体类路径
  #config-location: 指定mybatis的核心配置文件

springBoot原理分析

1.自动配置

Condition

Condition是在spring4.0增加的条件判断功能,通过这个功能可以实现选择性的创建Bean操作。

SpringBoot是如何知道要创建哪个Bean的?比如springBoot是如何知道要创建RedisTemplate的?

@SpringBootApplication
public class SpringJuint2Application {

    public static void main(String[] args) {
        //启动springboot的应用,返回spring的IOC容器
        ConfigurableApplicationContext context = SpringApplication.run(SpringJuint2Application.class, args);
        System.out.println(context.getBean("redisTemplate"));
    }

}

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
    <version>2.5.0</version>
</dependency>

案例:需求

在spring的IOC容器中有一个User的Bean,现要求:

1.导入Jedis坐标后,加载该Bean,没导入,则不加载

@SpringBootApplication
public class SpringJuint2Application {

    public static void main(String[] args) {
        //启动springboot的应用,返回spring的IOC容器
        ConfigurableApplicationContext context = SpringApplication.run(SpringJuint2Application.class, args);
        System.out.println(context.getBean("redisTemplate"));
        System.out.println(context.getBean("user"));
    }

}
ClassConditon类
public class ClassConditon implements Condition {
    @Override
    public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
        //1.需求导入Jedis坐标后创建Bean
        //2.判断redis.clients.jedis.Jedis文件是否存在
        boolean flag=true;
        try {
            Class<?> cls = Class.forName("redis.clients.jedis.Jedis");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            flag=false;
        }

        return flag;
    }
}
UserConfig类
@Configuration
public class UserConfig {

    @Bean
    @Conditional(ClassConditon.class)
    public User user(){
        return new User();
    }

}

2.将类的判断定义为动态的。判断哪个字节码文件存在可以动态指定。

ClassConditon类
public class ClassConditon implements Condition {
    /**
     *
     * @param conditionContext 上下文对象.用于获取环境,IOC容器,ClassLoader
     * @param annotatedTypeMetadata 注解的元对象,可以获取注解定义的属性值
     * @return
     */
    @Override
    public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
        //1.需求导入Jedis坐标后创建Bean
        //2.判断redis.clients.jedis.Jedis文件是否存在
        /*boolean flag=true;
        try {
            Class<?> cls = Class.forName("redis.clients.jedis.Jedis");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            flag=false;
        }

        return flag;*/
        Map<String, Object> map = annotatedTypeMetadata.getAnnotationAttributes(ConditionOnClass.class.getName());
        String[] value = (String[])map.get("value");

        boolean flag=true;
        try {
            for (String item:value){
                Class<?> cls = Class.forName(item);
            }

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            flag=false;
        }

        return flag;
    }
}
ConditionOnClass类
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Conditional(ClassConditon.class)
public @interface ConditionOnClass {
    String[] value();
}
UserConfig类
@Configuration
public class UserConfig {

    @Bean
    @ConditionOnClass("redis.clients.jedis.Jedis")
    public User user(){
        return new User();
    }

}

springBoot切换内置Web服务器

Springboot环境中默认使用tomcat作为内置服务器,其实springboot提供了4种内置服务器供我们选择,我们可以很方便的切换。

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
   <!-- 排除tomcat依赖-->
    <exclusions>
        <exclusion>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <groupId>org.springframework.boot</groupId>
        </exclusion>
    </exclusions>
</dependency>
<!--加入netty服务器-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jetty</artifactId>
</dependency>

SpringBoot自动配置

@Enable*注解

SpringBoot中提供了很多Enable开头的注解,这些注解都是用于动态启动某些功能的。而其底层原理是使用@Import注解导入一些配置类,实现Bean的动态加载。

SpringBoot是否可以直接获取Jar包中定义的Bean?(第三方jar包里面的bean)

Userconfig类

@Configuration
public class UserConfig {
    @Bean
    public User user(){
        return new User();
    }

}
SpringBootApplicationTest类
/**
 * @componentScan扫描范围:当前引导类所在包及子包
 * com.etc.springboot
 * com.etc.config
 * //1.使用@componentScan重新包扫描一下
 * //2.使用@Import注解,加载类,这些类都会被spring创建,并放入容器中
 */
//@SpringBootApplication
//@Import(UserConfig.class)
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan("com.etc.config")
public class SpringBootApplicationTest {
    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(SpringBootApplicationTest.class, args);
        Object user = context.getBean("user");
        System.out.println(user);

    }

}

springBoot自动配置之@EnableAutoConfiguration注解

2.监听机制

java中的事件监听zhi自定义了以下几个角色:

1.事件:Event,继承java.util.EventObject类的对象

3.启动流程

springboot监控actuator基本使用



这篇关于SpringBoot学习的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程