Spring注解系列十八:属性赋值-@PropertySource 野性酷女 2022-02-03 01:23 286阅读 0赞 1、创建配置文件person.properties person.name=李四 person.age=20 2、使用@PropertySource读取外部配置文件中的k/v保存到运行的环境变量中;加载完外部的配置文件以后使用$\{\}取出配置文件的值。@PropertySource是可重复注解。也可以用@PropertySources注解指定多个PropertySource加载多个配置文件。 <context:property-placeholder location="classpath:person.properties"/> @PropertySource(value={"classpath:/person.properties"}) @Configuration public class MainConfigOfPropertyValues { @Bean public Person person(){ return new Person(); } } 3、修改Person //3、可以写${};取出配置文件【properties】中的值(在运行环境变量里面的值) @Value("${person.name}") private String name; @Value("${person.age}") private Integer age; 4、测试 @Test public void test01(){ AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfigOfPropertyValues.class); String[] definitionNames = applicationContext.getBeanDefinitionNames(); for (String name : definitionNames) { System.out.println(name); } Person person = (Person) applicationContext.getBean("person"); System.out.println(person); ConfigurableEnvironment environment = applicationContext.getEnvironment(); String property = environment.getProperty("person.name"); System.out.println(property); applicationContext.close(); } ![在这里插入图片描述][watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2xpemhpcWlhbmcxMjE3_size_16_color_FFFFFF_t_70] [watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2xpemhpcWlhbmcxMjE3_size_16_color_FFFFFF_t_70]: /images/20220203/b1ed4dc66c624e7dbe7632d491acca4a.png
还没有评论,来说两句吧...