SpringBoot默认加载配置文件名为:application.properties和application.yml,如果需要使用自定义的配置文件,则通过@PropertySource注解指定。
JavaBean:
package org.springboot.model; import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component; @Component
@ConfigurationProperties(prefix = "pet")
@Data
// 自定义配置文件路径
@PropertySource(value = {"classpath:config/pet.properties"})
public class Pet {
private String name;
private String type;
}
pet.properties(./resources/config/pet.properties)
pet.name=haha
pet.type=dog
测试代码:
package org.springboot; import org.junit.Test;
import org.junit.runner.RunWith;
import org.springboot.model.Pet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class)
@SpringBootTest
public class DemoApplicationTests {
@Autowired
Pet pet; // 指定其他配置文件
@Test
public void testPet() {
System.out.println(pet);
} }
执行结果:
Pet(name=haha, type=dog)