SpringBoot的简单的配置:加载配置文件并设置其中的属性,和自定义日期格式转换器

本文详细介绍如何在SpringBoot中配置启动端口、访问路径及加载多种配置文件,包括application.properties和person.properties,演示如何使用@Value和@ConfigurationProperties进行属性注入。

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

1.配置SpringBoot的启动端口和访问路劲

开发环境:JDK1.8、Maven3.6.1、eclipse
在resource文件下 创建application.properties文件(注意:SpringBoot是使用约定优于配置的方式).

这里是application.peoperties文件中的内容
#配置当前SpringBoot的启动端口为9090
server.port=9090
#设置当前SpringBoot的访问的根路径,例如:http:localhost:9090/properties+你的@RequestMapping路径
server.context-path=/properties

当前项目的pom文件

   <properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>
	
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.2.4.RELEASE</version>
		<relativePath />
	</parent>
	
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
				</configuration>
			</plugin>
		</plugins>
	</build>

当前项目的Application文件

@SpringBootApplication
@RestController
public class Application
{
	@RequestMapping("hi")
	public String hi() {
		return "Hello World!";
	}
    public static void main( String[] args )
    {
        SpringApplication.run(Application.class ,args);
    }
}

测试修改后的端口和访问路劲
此时访问的路径为:http://localhost:9090/properties/hi

2.加载application.properties中定义的属性

这里是application.peoperties文件中的内容,向其中添加
#\u5F20\u4E09的实际值为张三,(使用了UTF-8编码转义后)
user.username=\u5F20\u4E09
#设置密码
user.userpwd=12345

Application类中添加

	//使用@Value可以用来解析当前application.properties中配置的属性,并将解析的值注入当前属性中
	@Value("${user.username}")//这里如果使用user.name 会默认使用当前计算机的用户名例如:admin
	String userName;
	@Value("${user.userpwd}")
	String userPwd;
	
	@RequestMapping("/user")
	public String user() {
		return "用户名:"+userName+",密码:"+userPwd;
	}

测试读取并使用配置
访问http://localhost:9090/properties/user
结果:用户名:张三,密码:12345

3.加载其他的配置文件中定义的属性并注入到对象中(当前对象初始化的时候会有初始值)

在当前项目中添加新的实体类Person

import java.util.Date;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

/**
 * @description 创建加载person.properties配置文件,并有初始值
 * @author hy
 * @date 2019-08-08
 */
@Component//使用该注解的时候会被当前的SpringBoot加载并实例化出来
@PropertySource(value = "classpath:person.properties") // 加载类路径中的person.properties文件,也可以放在一个文件中
@ConfigurationProperties(prefix = "person") // 加载的时候自动消除前缀person,获得的属性自动注入当前类属性中
public class Person {
	private String name;// 用户名
	private Integer age;// 年龄
	private Date birth;// 出生日期
	private Boolean onWork;// 是否在职

	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;
	}

	public Date getBirth() {
		return birth;
	}

	public void setBirth(Date birth) {
		this.birth = birth;
	}

	public Boolean getOnWork() {
		return onWork;
	}

	public void setOnWork(Boolean onWork) {
		this.onWork = onWork;
	}

	@Override
	public String toString() {
		return "Person [name=" + name + ", age=" + age + ", birth=" + birth + ", onWork=" + onWork + "]";
	}
}

在当前项目中resource文件中添加person.properties文件(该文件用来填充Person类中的属性),此时person.properties配置如下
person.name=\u674E\u56DB
person.age=22
person.birth=2019-08-08
person.onWork=true

由于使用了birth(Date类型的)属性,所以在当前的项目中需要添加Date类型的转换器DateConvert

import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;

@Component
public class DateConvert implements Converter<String, Date> {
	 final SimpleDateFormat[] formats = { 
			new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"),
			new SimpleDateFormat("yyyy-MM-dd") 
	};

	@Override
	public Date convert(String source) {
		Date date = null;
		synchronized (formats) {
			for (SimpleDateFormat format : formats) {
				try {
					date = format.parse(source);
				} catch (Exception e) {
					continue;
				}
			}
		}
		return date;
	}

}

当前DateConvert使用了@Component和实现了Converter<String, Date>所以当前类会被SpringBoot加载并注册到转换器中,当遇到类型为Date的时候会自动进行调用当前转换器进行转换

在当前Application启动类中添加

   @Autowired
	Person person;

	@RequestMapping("/person")
	public String person() {
		return person.toString();
	}

测试结果:
访问路径http://localhost:9090/properties/person
Person [name=李四, age=22, birth=Thu Aug 08 00:00:00 CST 2019, onWork=true]

总结:
1.使用SpringBoot加载默认的配置文件application.properties时可以使用@Value(${“key”})的方式加载属性值

2.使用SpringBoot加载配置文件的时候必须放在resource文件中

3.使用SpringBoot加载非默认的配置文件的时候必须使用@PropertySource(value = "classpath:需要加载的配置文件的路劲") ,再注入属性的时候可以使用@ConfigurationProperties(prefix = "前缀")的方式加载(此时出现不一致的属性的时候会默认注入null,当值不是包装类的时候会出现错误)

4.使用SpringBoot加载配置文件中的日期时需要自定义日期转换器实现Converter接口

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值