Spring Boot 核心-外部配置

Spring Boot可以使用properties文件、yaml文件或者命令行参数作为外部配置。

1 命令行参数配置

Spring Boot可以基于jar包运行,打成jar包可以通过下面命令运行:

java -jar xxx.jar

可以通过下面命令修改tomcate端口:

java -jar xx.jar --server.port=9090

2 常规属性配置

常规Spring环境下,注入properties文件里的值的方式:

  1. 通过@PropertySource指明文件位置。
  2. 通过@Value注入值。

在Spring Boot环境下:

  1. 在application.properties中定义属性。
  2. 通过@Value注入值。

3 类型安全的配置(基于properties)

使用@Value这个注入属性在实际开发中有点麻烦,如果多个地方用到这个属性就需要注入多次。

Spring Boot提供了基于类型安全的配置方式,通过@ConfigurationProperties将properties属性和一个Bean及其属性关联起来。

实战

  1. 新建Spring Boot项目
  2. 在pom中添加
<dependency>  
      <groupId>org.springframework.boot</groupId>  
      <artifactId>spring-boot-configuration-processor</artifactId>  
      <optional>true</optional>  
</dependency>
  1. 在application.properties中添加配置
author.name=wyh
author.age=30
  1. 类型安全的Bean
package com.chenfeng.xiaolyuh.properties;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix = "author")// prefix指定properties的前缀,
public class AuthorSettings {
	private String name;
	
	private long age;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public long getAge() {
		return age;
	}

	public void setAge(long age) {
		this.age = age;
	}
}
  1. 校验代码
package com.chenfeng.xiaolyuh;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.chenfeng.xiaolyuh.properties.AuthorSettings;

@SpringBootApplication // 这个是Spring Boot项目的核心注解,主要是开启自动配置。
@RestController
public class SpringBootStudentApplication {

	@Autowired // 通过注解直接注入配置类
	private AuthorSettings authorSettings; 
	
	@RequestMapping("/")
	public String index() {
		return "Hello World!  " + authorSettings.getName() + "::" + authorSettings.getAge();
	}

	// 标准的JAVA应用main方法,主要作用作为项目启动的入口
	public static void main(String[] args) {
		SpringApplication.run(SpringBootStudentApplication.class, args);
	}

}

参考

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值