springboot项目配置文件属性变量引用方式${}和@@用法与区别

本文详细解析了SpringBoot中${}

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

${}和@@都是springboot引用属性变量的方式,具体区别与用法:

1、${}常用于pom.xml,和 src/main/resources/application.properties等默认配置文件的属性变量引用。

语法为:field_name=${field_value}

pom.xml示例:

<properties>
    <dubbo.version>2.7.0</dubbo.version>
</properties>

 <dependencies>
     <dependency>
         <groupId>org.apache.dubbo</groupId>
          <artifactId>dubbo</artifactId>
          <version>${dubbo.version}</version>
     </dependency>
 </dependencies>

application.properties示例:

#logback日志配置
log.config.address=classpath:config/logback-spring.xml
logging.config=${log.config.address}

2、@@方式常用于引用springboot非默认配置文件(即其他配置文件)中的变量,是springboot为替代${}属性占位符产生,原因是${}会被maven处理,所以引用非默认配置文件时起不到引用变量的作用。

语法为:field_name=@field_value@

示例:在实际项目开发中,为了在不同环境进行测试,我们会在src/main/resources目录下创建config文件夹,并在config中创建多个properties文件,例如:local.properties, development.properties, production.properties,当我们在src/main/resources/application.properties文件中引用src/main/resources/config/local.properties的属性变量时,就要使用@@方式

#端口配置
server.port=@server.port.web@

#logback日志配置
logging.config=@logging.config@

 

在Spring Boot项目中,将配置文件(通常是application.properties或application.yml)中的属性读取到静态变量中通常是在启动类(如@SpringBootApplication或@RestController)中完成的。你可以使用`@Value`注解或者`Properties`类配合`Environment`接口来实现这一目标。 1. 使用`@Value`注解: ```java @Component public class AppConfig { @Value("${property.name}") private static String propertyName; // 可以通过getter方法访问静态变量 public static String getPropertyName() { return propertyName; } } ``` 在这个例子中,`${property.name}`是配置文件中的键,它的值会被自动注入到`propertyName`中。 2. 使用`Properties``Environment`: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.context.Environment; @Component public class AppConfig { private static Properties properties; @Autowired public AppConfig(ApplicationContext context, Environment env) { this.properties = new Properties(); env.getPropertySources().forEach(ps -> ps.forEach((key, value) -> properties.setProperty(key, value))); } public static String getProperty(String key) { return properties.getProperty(key); } } ``` 这里,我们先注入`ApplicationContext``Environment`,然后遍历环境中的所有属性源,将它们添加到`Properties`对象中。 无论哪种方式,建议将配置管理封装成单例或工具类,以便在整个应用中方便地获取配置信息。
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值