在项目中经常有一些配置项,Spring Boot默认为我们准备好了配置文件application.properties。
1、找到项目中src/main/resources目录下的application.properties,打开写入配置项
com.example.demo.title=冬夜读书示子聿 作者:陆游
com.example.demo.description=纸上得来终觉浅,绝知此事要躬行。
com.example.demo.keywords=中华古诗词
输入中文字符之后,会自动转成编码格式。
2、新建一个测试TestController类
package com.example.demo.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TestController
{
@Value("${com.example.demo.keywords}")
private String keywords;
@RequestMapping("/test")
public String showText()
{
System.out.println(keywords);
return "TestController!";
}
}
3、启动Spring Boot项目,在浏览器中输入http://localhost:8080/test/,可以看到控制台打印出来配置项信息:
但是这种形式在每个需要使用配置文件内容的地方都要重复的@Value注释一遍,能不能简便一点?可以。
1、新建一个配置文件类用@Component注释,并用@Value注入到类的成员变量中。
package com.example.demo.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class AppProperties
{
@Value("${com.example.demo.title}")
private String title;
@Value("${com.example.demo.description}")
private String description;
@Value("${com.example.demo.keywords}")
private String keywords;
public String getTitle()
{
return title;
}
public String getDescription()
{
return description;
}
public String getKeywords()
{
return keywords;
}
}
这里需要注意的是,因为用到了@Value注释,所以这个类使交由Spring管理的。因此使用new一个类的对象的方法是无法获取到值的。
// 因为用到了@Value注释,所以这个类使交由spring管理的。因此使用new一个类的对象的方法是无法获取到值的。
// 因为用到了@Value注释,所以这个类使交由spring管理的。因此使用new一个类的对象的方法是无法获取到值的。
AppProperties appProperties = new AppProperties();
System.out.println(appProperties.getTitle()); // 返回null
System.out.println(appProperties.getDescription()); // 返回null
正确做法,应该用 @Autowired注释
@Autowired
AppProperties appProperties;
2、打开之前编写的测试TestController,并修改为以下代码:
package com.example.demo.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.demo.config.AppProperties;
import com.example.demo.utils.SpringUtil;
@RestController
public class TestController
{
@Autowired
AppProperties appProperties;
@Value("${com.example.demo.keywords}")
private String keywords;
@RequestMapping("/test")
public String showText()
{
// 直接获取@Value注入的值
System.out.println(keywords);
// 通过从Spring管理的类中获取配置文件类AppProperties实例,进而获取配置项的值
System.out.println(appProperties.getTitle());
System.out.println(appProperties.getDescription());
return "TestController!";
}
}
3、启动Spring Boot项目,在浏览器中输入http://localhost:8080/test/,可以看到控制台打印出来配置项信息: