天天看點

Springboot自定義配置

Springboot架構實作了自動配置,在開發過程中,我們需要自定義一些配置可以用properties的形式進行配置,可以使用@Value注解來讀取自定義配置。

application.properties中添加自定義配置

Person.java

@Component
public class Person {
	@Value("${person.name}")
	private String name;
	@Value("${person.age}")
	private Integer age;
	@Value("${person.sex}")
	private String sex;
        //略去getter、setter和toString方法 
}
           

 application.properties

person.age=25
person.name=lisan
person.sex=male
           

測試類

@SpringBootTest
@RunWith(SpringRunner.class)
public class MyTest {
	@Autowired
	Person person;
	@Test
	public void jdbcTest() {
		System.out.println(person);
	}
}
           

結果

Springboot自定義配置

自定義配置檔案添加配置

person.properties

person.age=25
person.name=lisan
person.sex=male
           

Person.java添加@PropertySource注解

@PropertySource(value = { "classpath:person.properties" }, ignoreResourceNotFound = true)
           
Springboot自定義配置

效果和上面一樣

繼續閱讀