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

时间:2025-02-13 16:51:19

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

搭建SpringBoot环境

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

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

添加主函数

在根目录添加启动类

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添加配置文件
添加上开发环境(),生产环境(),测试环境()的配置文件
文件,说明使用prod后缀的配置文件

=prod

文件

=8080

文件

=8081

文件

=8082

配置文件类

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

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

配置文件类

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("${}")
	public void setPort(String port) {
		Properties.port = port;
	}
	
}

结果

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

参考

/mononoke111/article/details/81088472