spring boot之自定义properties文件并获取数据

本文介绍了一个基于Spring Boot的示例项目,演示如何从外部配置文件abc.properties加载属性到Java Bean,并通过@Controller注解提供HTTP接口访问这些属性。

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

1.新建配置文件abc.properties

 

author.name=yaoge
author.age=888888
author.address=sh1

 

 

2.定义AuthorSettings

 

package com.basic.demo;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

@Configuration
@ConfigurationProperties(prefix="author")
@PropertySource("classpath:abc.properties")
public class AuthorSettings {
	private String name;
	private Integer age;
	private String address;
	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 String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
	
}

    

 

3.controller

 

package com.basic.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * desc:简单controller
 * @date 2017-03-28 11:28:56
 * @author 磨练中龙
 *
 */
@RestController
@RequestMapping("/simple")
public class SimpleController {
	
	@Autowired
	private AuthorSettings authorSettings;
	
	@RequestMapping("/")
	public String index(){
		return authorSettings.getName()+"--"+authorSettings.getAge()+"--"+authorSettings.getAddress();
	}
}

   

 4.启动项目

    

/**
 * desc:项目启动入口
 * @date 2017-03-28 11:29:39
 * @author 磨练中龙
 *
 */
@SpringBootApplication
@EnableConfigurationProperties(AuthorSettings.class)
public class App {
	
	public static void main(String[] args) {
		SpringApplication.run(App.class, args);
	}
}

 

 

    八卦下: 

    

@ConfigurationProperties locations过期了,我们可以使用以下注解代替
@PropertySource("classpath:abc.properties") 

如果使用application.properties配置文件,可以只使用这个注解,定义好前缀即可,例如:
@ConfigurationProperties(prefix="author")

 

         

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值