springboot 加载自定义properties文件(@PropertySOurce)
**********************
相关注解
@PropertySource
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Repeatable(PropertySources.class)
public @interface PropertySource {
String[] value(); //加载文件位置
String name() default "";
boolean ignoreResourceNotFound() default false;
String encoding() default "";
Class<? extends PropertySourceFactory> factory() default PropertySourceFactory.class;
//自定义factory,默认不能加载yml文件,可自定义factory
}
**********************
示例
****************
属性文件
person.properties
person.name=瓜田李下
person.age=20
****************
pojo 层
Person
@Data
@Component
@ConfigurationProperties(prefix = "person")
@PropertySource(value = {"classpath:properties/person.properties"})
public class Person {
private String name;
private Integer age;
}
****************
controller 层
HelloController
@RestController
public class HelloController {
@Resource
private Person person;
@RequestMapping("/hello")
public String hello(){
System.out.println(person);
return "success";
}
}
**********************
使用测试
localhost:8080/hello
2020-07-09 20:35:22.908 INFO 6488 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2020-07-09 20:35:22.952 INFO 6488 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet : Completed initialization in 43 ms
Person(name=瓜田李下, age=20)