搞懂Spring配置,能减少一半配置问题吗?
摘要:案例 前置条件: 在 resources 目录下有 hellohello.properties 文件,文件内容如下: hello=nihao 案例一: 在 HelloController 类中通过 @PropertySource 注解引用
案例
前置条件:
在 resources 目录下有 hello/hello.properties 文件,文件内容如下:
hello=nihao
案例一:
在 HelloController 类中通过 @PropertySource 注解引用 properties 文件的内容,然后就可以通过 @Value 注解引用这个配置文件中的 hello 这个 key 了。
@PropertySource({"classpath:hello/hello.properties"})
@RestController
public class HelloController {
@Value("${hello}")
private String hello;
@GetMapping("/hello")
public String hello() {
return hello;
}
}
案例一执行的结果是返回 nihao 这个字符串。
案例二:
在 AnotherController 类中通过 @PropertySource 注解引用 properties 文件的内容,在 HelloController 中仍然可以通过 @Value 注解引用这个配置文件中的 hello 这个 key 。
@RestController
public class HelloController {
@Value("${hello}")
private String hello;
@GetMapping("/hello")
public String hello() {
return hello;
}
}
@RestController
@PropertySource({"classpath:hello/hello.properties"})
public class AnotherController {
// 省略代码
}
案例二返回的结果和案例一一致,这说明了只需要一个 Bean 通过 @PropertySource 注解引用了 properties 配置文件后,其它的 Bean 无需再使用@PropertySource 注解引用即可通过 @Value 注入其中的值。
