1 @Value注解和@PropertySource
可以使用@value注解给属性赋值,有三种用法
- 基本的数值
- spring表达式: #{}
- ${},取出配置文件中的值
@PropertySource: 用于加载配置文件
2 演示
- 提供一个配置文件放在classpath下: mysql.properties
mysql.host=localhost
mysql.username=root
mysql.password=rootroot
mysql.port=3306
- 提供一个类封装这些信息
@Data
public class MysqlConfigProperty {
@Value("mysql")
private String protocol;
@Value("${mysql.host}")
private String host;
@Value("${mysql.username}")
private String username;
@Value("${mysql.port}")
private String port;
@Value("${mysql.password}")
private String password;
}
- 主配置文件中,使用
@PropertySource
加载配置文件
@Configuration
@ComponentScan(value = {"study.wyy.spring.anno.learn"})
@PropertySource({"classpath:mysql.properties"})
public class MainConfig2 {
@Bean
public MysqlConfigProperty mysqlConfigProperty() {
return new MysqlConfigProperty();
}
}
- 测试
@Test
public void test01(){
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig2.class);
MysqlConfigProperty bean = applicationContext.getBean(MysqlConfigProperty.class);
Assert.assertThat(bean,notNullValue());
Assert.assertThat(bean.getHost(),equalTo("localhost"));
Assert.assertThat(bean.getPort(),equalTo("3306"));
Assert.assertThat(bean.getUsername(),equalTo("root"));
Assert.assertThat(bean.getProtocol(),equalTo("mysql"));
Assert.assertThat(bean.getPassword(),equalTo("rootroot"));
}