SpringBoot学习笔记-2:第二章 Spring Boot 配置(2)

简介: SpringBoot学习笔记-2:第二章 Spring Boot 配置

4、@ConfigurationProperties 与@Value 区别

image.png

属性名匹配规则

person.firstName
person.first-name
person.first_name
PERSON_FIRST_NAME
package com.mouday.bean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
 * 将配置文件中的属性映射到这个组件中
 */
@Component
// @ConfigurationProperties(prefix = "person")
public class Person {
    /**
     * <bean class="Person">
     *     <property name="name" value="Tom" />
     * </bean>
     *
     * value 支持
     * 字面量
     * ${key}从环境变量,配置文件中获取值
     * #{SpEL}表达式
     */
    @Value("Tom")
    private String name;
    @Value("#{12*2}")
    private Integer age;
    @Value("true")
    private Boolean sex;
    @Value("${person.birth}")
    private Date birth;
    private Map<String, Object> maps;
    private List<String> lists;
    private Dog dog;
    /**
    * 略setter/getter toString()
    */
}

打印结果

Person{name='Tom', age=24, sex=true, birth=Tue Dec 12 00:00:00 CST 2017,
maps=null, lists=null, dog=null}
• 1
• 2

配置文件注入值数据校验

import org.hibernate.validator.constraints.Email;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
@Component
@ConfigurationProperties(prefix = "person")
@Validated
public class Person {
    @Email
    private String name;
}

使用方式

  1. 只是在某个业务逻辑中获取一个配置文件中的某项值,使用@Value
  2. 专门编写一个 javaBean 来映射配置文件,那么使用@ConfigurationProperties

@Value 用法示例

package com.mouday.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
@Controller
@RestController
public class HelloController {
    @Value("${person.name}")
    private String name;
    @RequestMapping("/hello")
    @ResponseBody
    public String hello(){
        return "Hello world! " + this.name;
    }
}

5、@PropertySource、@ImportResource、@Bean

@ConfigurationProperties 默认加载全局配置

5.1、@PropertySource 加载指定配置文件

import org.springframework.stereotype.Component;
import org.springframework.context.annotation.PropertySource;
@Component
// @ConfigurationProperties(prefix = "person")
@PropertySource(value = {"classpath:person.properties"})
public class Person {}

5.2、@ImportResource 导入 Spring 配置文件

src/main/resources/beans.xml

<?xml version="1.0" encoding="utf-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                        http://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean name="dog" class="com.mouday.bean.Dog"/>
</beans>

@ImportResource 标注在配置类上

package com.mouday;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ImportResource;
@ImportResource(value = {"classpath:beans.xml"})
@SpringBootApplication
public class ApplicationMain {
    public static void main(String[] args) {
        SpringApplication.run(ApplicationMain.class, args);
    }
}

测试方法

package com.mouday;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class DemoApplicationTests {
    @Autowired
    private ApplicationContext context;
    @Test
    public void TestDog(){
        System.out.println(this.context.containsBean("dog"));
    }
}

5.3、@Bean 用于配置类中给容器添加组件

package com.mouday.config;
import com.mouday.bean.Dog;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
 * @Configuration 指明当前类是一个配置类
 * 替代Spring的配置文件
 */
@Configuration
public class MyConfig {
    // 将方法的返回值添加到容器,容器中组件默认id是方法名
    @Bean
    public Dog dog(){
        return new Dog();
    }
}

Spring 推荐使用全注解方式给容器添加组件

6、配置文件占位符

RandomValuePropertySource 配置文件中可以使用随机数

${random.value}
${random.int}
${random.uuid}
${random.long}
${random.int(10)}
${random.int[1024,65536]}

属性配置占位符

app.name=MyApp
app.description=${app.name:默认值}

7、Profile 多环境支持


Profile 对不同环境提供不同配置功能的支持


1、多 Profile 文件


application-{profile}.properties


默认使用

application.properties

通过 spring.profiles.active=prod 指定配置文件


eg:

application.properties


server.port=8080

spring.profiles.active=prod


application-dev.properties


server.port=8081


application-prod.properties


server.port=8082


2、yaml 文档块模式


application.yml

server:
  port: 8080
spring:
  profiles:
    active: dev
---
server:
  port: 8081
spring:
  profiles: dev
---
server:
  port: 8082
spring:
  profiles: prod

3、激活方式

1、命令行
--spring.profiles.active=dev
2、配置文件
spring.profiles.active=dev
3、jvm参数
-Dspring.profiles.active=dev



相关文章
|
2月前
|
前端开发 Java 应用服务中间件
《深入理解Spring》 Spring Boot——约定优于配置的革命者
Spring Boot基于“约定优于配置”理念,通过自动配置、起步依赖、嵌入式容器和Actuator四大特性,简化Spring应用的开发与部署,提升效率,降低门槛,成为现代Java开发的事实标准。
|
2月前
|
前端开发 Java 微服务
《深入理解Spring》:Spring、Spring MVC与Spring Boot的深度解析
Spring Framework是Java生态的基石,提供IoC、AOP等核心功能;Spring MVC基于其构建,实现Web层MVC架构;Spring Boot则通过自动配置和内嵌服务器,极大简化了开发与部署。三者层层演进,Spring Boot并非替代,而是对前者的高效封装与增强,适用于微服务与快速开发,而深入理解Spring Framework有助于更好驾驭整体技术栈。
|
2月前
|
搜索推荐 JavaScript Java
基于springboot的儿童家长教育能力提升学习系统
本系统聚焦儿童家长教育能力提升,针对家庭教育中理念混乱、时间不足、个性化服务缺失等问题,构建科学、系统、个性化的在线学习平台。融合Spring Boot、Vue等先进技术,整合优质教育资源,提供高效便捷的学习路径,助力家长掌握科学育儿方法,促进儿童全面健康发展,推动家庭和谐与社会进步。
|
2月前
|
JavaScript Java Maven
【SpringBoot(二)】带你认识Yaml配置文件类型、SpringMVC的资源访问路径 和 静态资源配置的原理!
SpringBoot专栏第二章,从本章开始正式进入SpringBoot的WEB阶段开发,本章先带你认识yaml配置文件和资源的路径配置原理,以方便在后面的文章中打下基础
344 3
|
2月前
|
XML Java 应用服务中间件
【SpringBoot(一)】Spring的认知、容器功能讲解与自动装配原理的入门,带你熟悉Springboot中基本的注解使用
SpringBoot专栏开篇第一章,讲述认识SpringBoot、Bean容器功能的讲解、自动装配原理的入门,还有其他常用的Springboot注解!如果想要了解SpringBoot,那么就进来看看吧!
446 2
|
3月前
|
人工智能 Java 机器人
基于Spring AI Alibaba + Spring Boot + Ollama搭建本地AI对话机器人API
Spring AI Alibaba集成Ollama,基于Java构建本地大模型应用,支持流式对话、knife4j接口可视化,实现高隐私、免API密钥的离线AI服务。
2876 1
基于Spring AI Alibaba + Spring Boot + Ollama搭建本地AI对话机器人API
|
3月前
|
缓存 Java 应用服务中间件
Spring Boot配置优化:Tomcat+数据库+缓存+日志,全场景教程
本文详解Spring Boot十大核心配置优化技巧,涵盖Tomcat连接池、数据库连接池、Jackson时区、日志管理、缓存策略、异步线程池等关键配置,结合代码示例与通俗解释,助你轻松掌握高并发场景下的性能调优方法,适用于实际项目落地。
631 5
存储 JSON Java
540 0
|
3月前
|
人工智能 Java 开发者
【Spring】原理解析:Spring Boot 自动配置
Spring Boot通过“约定优于配置”的设计理念,自动检测项目依赖并根据这些依赖自动装配相应的Bean,从而解放开发者从繁琐的配置工作中解脱出来,专注于业务逻辑实现。
1411 0
|
Java 测试技术 数据库
SpringBoot - 不要在 Spring Boot 集成测试中使用 @Transactional
SpringBoot - 不要在 Spring Boot 集成测试中使用 @Transactional
512 0
SpringBoot - 不要在 Spring Boot 集成测试中使用 @Transactional