日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

@value 静态变量_Spring注解驱动开发之八——@Value属性赋值、@PropertySource 加载外部配置文件...

發布時間:2025/3/20 39 豆豆
生活随笔 收集整理的這篇文章主要介紹了 @value 静态变量_Spring注解驱动开发之八——@Value属性赋值、@PropertySource 加载外部配置文件... 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

本文包含以下內容:

  • 建立新的配置類

  • 建立新的測試方法

  • 通過@Value 進行賦值

  • 通過@PropertySource? 加載配置文件,并進行注入

  • 拓展@Value??、@PropertySource?

  • 1.建立新的配置類

    建立新的配置類,@Configuration指定為配置類?,@Bean加載Person類,為測試做準備,代碼如下:@Configurationpublic class MainConfigOfPropertyValues { @Bean public Person person(){ return new Person(); }}

    2.建立新的測試方法

    建立測試方法,獲取并打印Person 的Beanpublic class IOCTest_PropertyValue { AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfigOfPropertyValues.class); @Test public void test01(){ printBeans(applicationContext); System.out.println("============="); Person person = (Person) applicationContext.getBean("person"); System.out.println(person); } private void printBeans(AnnotationConfigApplicationContext applicationContext){ String[] definitionNames = applicationContext.getBeanDefinitionNames(); for (String name : definitionNames) { System.out.println(name); } }}測試類運行結果如下,可以看到默認情況下person 這個Bean 所有的字段都為空。下面將進行賦值

    3.通過@Value?進行賦值

    在xml配置文件可以通過bean 標簽中包含property進行屬性賦值<bean id="person" class="com.atguigu.bean.Person" scope="prototype" > <property name="age" value="18">property> <property name="name" value="zhangsan">property> bean>在注解開發中可以使用@Value ?對屬性進行賦值。其中可以賦值1.基本數據類型@Value("張三")private String name;2.可以寫SpEL;#{}?,即sping 的表達式@Value("#{20-2}")private Integer age;3.可以寫${};取出配置文件【properties】中的值(在運行環境變量里面的值)@Value("${person.nickName}")private String nickName;運行結果如下,成功賦值

    4.通過@PropertySource? 加載配置文件,并進行注入

    在xml 配置文件時,可以通過context:property-placeholder標簽,引入配置文件。<context:property-placeholder location="classpath:person.properties"/>1.在注解開發中,可使用@PropertySource 加載外部配置文件@PropertySource(value={"classpath:/person.properties"})2.創建屬性文件person.propertiesperson.nickName=小李四即可通過@Value + ${}獲取到配置的文件的值,或使用容器的getEnvironment()方法進行調用getProperty("person.nickName");獲取配置文件中的內容。ConfigurableEnvironment environment = applicationContext.getEnvironment();String property = environment.getProperty("person.nickName");System.out.println(property);添加測試運行結果如下:

    5.拓展@Value? 、@PropertySource?

    @Value?靜態變量賦值

    在處理靜態變量時候,使用上面的@Value的用法是無法獲取到配置文件中的數據的,只能獲取到null,所以要進行如下更改。

    @PropertySource注解的地址可以是以下兩種:

    ?classpath路徑:"classpath:/com/myco/app.properties"

    ?文件對應路徑:"file:/path/to/file"

    -END-

    可以關注我的公眾號,免費獲取價值1980元學習資料

    點擊“在看”,學多少都不會忘~

    總結

    以上是生活随笔為你收集整理的@value 静态变量_Spring注解驱动开发之八——@Value属性赋值、@PropertySource 加载外部配置文件...的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。