SpringBoot学习--使用配置文件对静态变量赋值

SpringBoot学习–使用配置文件对静态变量赋值

搭建SpringBoot环境

建立maven项目。向pom.xml文件引入相关包

	<!--spring-boot 依赖的父工程 -->
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.3.RELEASE</version>
	</parent>
	
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-thymeleaf</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
	</dependencies>

添加主函数

在根目录添加Appilcation.java启动类

package com.pzr.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import com.pzr.demo.staticclass.Properties;

/**
 * 启动类
 * @author ASUS
 *
 */
@SpringBootApplication
public class Appilcation {
	
	public static void main(String args[]){
        SpringApplication.run(Appilcation.class, args);
		System.out.println("使用端口:"+Properties.port);
	}
}

添加配置文件

在src/main/resources添加配置文件application.properties
添加上开发环境(application-dev.properties),生产环境(application-prod.properties),测试环境(application-test.properties)的配置文件
application.properties文件,说明使用prod后缀的配置文件

spring.profiles.active=prod

application-dev.properties文件

server.port=8080

application-prod.properties文件

server.port=8081

application-test.properties文件

server.port=8082

配置文件类

本文是使用@Value注解为静态变量赋值
注意:

  1. 配置文件类必须使用@Component注解,纳入到容器管理中来。
  2. 使用@Value为set方法注解,set方法不使用static进行修饰。

配置文件类Properties.java

package com.pzr.demo.staticclass;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class Properties {

	public static String port;

	
	@Value("${server.port}")
	public void setPort(String port) {
		Properties.port = port;
	}
	
}

结果

通过主配置文件application.properties切换不同环境的配置文件如:spring.profiles.active=prod则是使用application-prod.properties文件中的配置,控制台会打印“使用端口:8081”

参考

https://blog.csdn.net/mononoke111/article/details/81088472

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

-贫寒豌豆

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值