@PropertySource是Spring boot为了方便引入properties配置文件提供的一个注解,可以将某个properties配置文件中的值,存储到Spring的 Environment中。我们可以通过Environment、或者@Value、或者@Value+@ConfigurationProperties方式来获取properties配置文件中的值。
配置文件config.properties
jdbc.driver = oracle.jdbc.driver.OracleDriver jdbc.username= sassy jdbc.password = password jdbc.url = jdbc\:oracle\:thin\:@(DESCRIPTION\=(ADDRESS\=(PROTOCOL\=TCP)(HOST\=10.221.129.208)(PORT\=1523))(CONNECT_DATA\=(SERVICE_NAME\=otatransuser)))
用法1:Environment
@Configuration @PropertySource("classpath:jdbc.properties") public class PropertiesWithJavaConfig { @Autowired private Environment env; } //后续就能用以下语句,得到相应的属性值 String driver = env.getProperty("jdbc.driver");
用法2:@PropertySource + @Value
@Configuration @PropertySource("classpath:jdbc.properties") public class PropertiesWithJavaConfig { @Value(${jdbc.driver}) private String driver; @Value(${jdbc.url}) private String url; @Value(${jdbc.username}) private String username; @Value(${jdbc.password}) private String password; //(TBC)要想使用@Value 用${}占位符注入属性,这个bean是必须的,这个就是占位bean,另一种方式是不用value直接用Envirment变量直接getProperty(‘key‘) @Bean public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { return new PropertySourcesPlaceholderConfigurer(); } }
用法3:@PropertySource + @Value + @ConfigurationProperties
使用@Value注解方式有一个不太友好的地方就是,当项目中有大量的属性进行配置的时候,我们需要一个个的在类的字段中增加@Value注解,这样确实很费劲,不过我们可以通过Springboot提供的@ConfigurationProperties注解解决这个问题。
比如我们配置的prefix = "jdbc",PropertiesWithJavaConfig类中有一个driver字段,则driver字段需要匹配的属性是 --> prefix+字段 = jdbc.driver
@Configuration @PropertySource("classpath:jdbc.properties") @ConfigurationProperties(prefix ="jdbc") public class PropertiesWithJavaConfig { private String driver; private String url; private String username; private String password; //... }
原文:https://www.cnblogs.com/frankcui/p/13929573.html