如果需要把application.properties配置中的一些配置内容,独立出来,我们可以使用PropertySource来读取单独的配置文件,仅支持properties类型,yml需要自己手动代码再实现
贴代码
person.java
package com.shrimpking.demo1;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.Map;
/**
* Created by IntelliJ IDEA.
*
* @Author : Shrimpking
* @create 2023/12/22 11:27
*/
@Data
@Component
@PropertySource(value = "classpath:person.properties")
public class Person
{
@Value("${person.name}")
private String name;
@Value("${person.age}")
private Integer age;
@Value(("${person.boss}"))
private Boolean boss;
//不支持@value
private Map<String,Object> maps;
//不支持@value
private List<String> lists;
//不支持@value
private Dog dog;
}
dog.java
package com.shrimpking.demo1;
import lombok.Data;
/**
* Created by IntelliJ IDEA.
*
* @Author : Shrimpking
* @create 2023/12/22 11:29
*/
@Data
public class Dog
{
private String name;
private Integer age;
}
application.properties
server.port=8089
person.properties
person.name=zhangsan
person.age = 18
person.boss = false
person.maps.k1 = v1
person.maps.k2 = v2
person.lists = a,b,c
person.dog.name = tom
person.dog.age = 2
controller.java
package com.shrimpking.demo1;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* Created by IntelliJ IDEA.
*
* @Author : Shrimpking
* @create 2023/12/22 11:32
*/
@RestController
public class TestController
{
@Autowired
private Person person;
@GetMapping("/test")
public String test(){
return person.toString();
}
}
启动类
package com.shrimpking.demo1;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
@SpringBootApplication
public class Demo1Application
{
public static void main(String[] args)
{
SpringApplication.run(Demo1Application.class, args);
}
}
注意,使用propertysource时,只能配合使用@value来获取值,并且只能获取简单类型的值,复杂类型,比如数据,map,类对象等不支持。
另外propertysource仅支持properties类型的,yml需要自己增加代码支持。

307

被折叠的 条评论
为什么被折叠?



