@Value-赋值,@PropertySource读取配置文件

配置

复制代码
//使用@PropertySource读取外部配置文件中的k/v保存到运行的环境变量中;加载完外部的配置文件以后使用${}取出配置文件的值
@PropertySource(value = {"classpath:/entity1.properties"})
@Configuration
public class MyConfig2 {

    @Bean
    public Entity1 entity1(){
        return new Entity1();
    }
}
复制代码
复制代码
@Data
public class Entity1 {

    /**
     *  @Value 的三种写法
     *  1.基本的数值
     *  2.#{}  SpEL(Spring 表达式语言)
     *  3.${}  读取配置文件中数值
     */
    
    @Value("张三")
    private String name;

    @Value("#{100-30}")
    private int age;

    @Value("${entity1.address}")
    private String address;
}
复制代码
entity1.address=吉林长春

 

输出

复制代码
 @Test
    public void Test1(){
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MyConfig2.class);
        String[] beanDefinitionNames = applicationContext.getBeanDefinitionNames();
        for (String beanDefinitionName : beanDefinitionNames) {
            System.out.println(beanDefinitionName);
        }
        Entity1 entity1 = (Entity1)applicationContext.getBean("entity1");
        System.out.println(entity1);
    }
复制代码

输出结果

 

 

@PropertySource注解值可以写数组填写多个文件
也可以用@PropertySources注解填写多个@PropertySource

 

posted @   Dabo丶  阅读(177)  评论(0编辑  收藏  举报
(评论功能已被禁用)
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示