第一种
- 在
application.properties
中增加配置
mrbird.blog.name=mrbird's blog
mrbird.blog.title=Spring Boot
mrbird.blog.wholeTitle=${mrbird.blog.name}--${mrbird.blog.title}
- 新建java class
package com.springboot.bean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class BlogProperties {
@Value("${mrbird.blog.name}")
private String name;
@Value("${mrbird.blog.title}")
private String title;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
- 测试代码
@RequestMapping("/1")
String index1() {
return blogProperties.getName()+","+blogProperties.getTitle();
}
第二种
- 在
application.properties
中增加配置
mrbird.blog.name=mrbird's blog
mrbird.blog.title=Spring Boot
mrbird.blog.wholeTitle=${mrbird.blog.name}--${mrbird.blog.title}
- 新建java class
package com.springboot.bean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@ConfigurationProperties(prefix="mrbird.blog")
@Component
public class ConfigBean {
private String name;
private String title;
private String wholeTitle;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getWholeTitle() {
return wholeTitle;
}
public void setWholeTitle(String wholeTitle) {
this.wholeTitle = wholeTitle;
}
}
- 测试代码
@RequestMapping("/2")
String index2() {
return configBean.getName()+","+configBean.getTitle();
}
第三种
- resource下新建
test.properties
文件,内容如下
test.name=KangKang
test.age=25
- 新增java class
package com.springboot.bean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix="test")
@PropertySource("classpath:test.properties")
public class TestConfigBean {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
- 测试代码
RequestMapping("/")
String index() {
return testConfigBean.getName()+","+testConfigBean.getAge();
}
test.properties在resource下。