读取配置文件
@Value
1 2
| @Value("${phj233.name}") private String name;
|
必须是Bean,不能为final 或 static
读取的配置在,application.yml中必须存在
@ConfigurationProperties
1 2 3 4 5 6
| @Component @ConfigurationProperties(prefix = "phj233") public class ValueTest { private String name; private Integer age; }
|
必须被Spring托管
属性自动被key中对应的值赋值
Environment接口
1 2 3 4 5 6 7 8
| public class ValueTest { @Resource private Environment env;
public void test() { String PHJ233_NAME = env.getProperty("phj233.name"); } }
|
@PropertySources
获取自己新建的phj233.properties文件
1 2 3 4 5 6 7
| @PropertySources({ @org.springframework.context.annotation.PropertySource(value = "classpath:phj233.properties", encoding = "UTF-8"), }) public class ValueTest { @Value("${phj233.name}") private String name; }
|
只能获取properties文件
获取自定义yaml文件的配置
1 2 3 4 5 6 7 8 9 10 11 12
| public class ValueTest { @Bean public static PropertySourcesPlaceholderConfigurer yaml() { PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer(); YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean(); yaml.setResources(new ClassPathResource("phj233.yml")); configurer.setProperties(Objects.requireNonNull(yaml.getObject())); return configurer; } @Value("${phj233.name}") private String name; }
|