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

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")

         

猜你喜欢

转载自zzgo20141028.iteye.com/blog/2366494