Spring如何通過注解引入外部資源(PropertySource?Value)
更新時間:2023年07月20日 09:05:51 作者:一只小小鳥
這篇文章主要為大家介紹了Spring通過注解@PropertySource和@Value引入外部資源的方法實現(xiàn)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
spring如何引入外部資源文件
spring中如何引入外部資源文件,在使用xml配置是常用的方法,即:
<context:property-placeholder location="classpath*:spring.properties" file-encoding="utf-8"/>
然后可以在spring的xml文件中使用資源文件的屬性值,比如配置Bean的屬性spring-bean.xml
<bean id="person" class="com.sff.app.bean.Person" scope="prototype"> <property name="name" value="${person.name}"/> <property name="age" value="${person.age}"/> </bean>
那么如何利用注解來實現(xiàn)呢?
@PropertySource
- 在配置類中使用
@PropertySource
引入外部資源文件
@Configuration @PropertySource({"classpath:spring.properties"}) public class AppConfig4 { @Bean public Person person() { return new Person("kate", 12); } }
- 申明我們的資源文件
spring.properties
person.nickName=aaa
- 實體Bean中注入資源文件屬性值
import lombok.Data; import org.springframework.beans.factory.annotation.Value; @Data public class Person { private String name; private Integer age; @Value("${person.nickName}") private String nickName; public Person() { } public Person(String name, Integer age) { this.name = name; this.age = age; } }
- 單元測試
@Test public void testProperties() { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig4.class); Person person = ctx.getBean(Person.class); System.out.println(person); }
以上就是Spring如何通過注解引入外部資源(PropertySource Value)的詳細(xì)內(nèi)容,更多關(guān)于Spring注解引入外部資源的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Mybatis輸入輸出映射及動態(tài)SQL Review
這篇文章主要介紹了Mybatis輸入輸出映射及動態(tài)SQL Review,需要的朋友可以參考下2017-02-02MyBatis查詢數(shù)據(jù)庫語句總結(jié)
MyBatis是一種持久化框架,可以與許多不同類型的關(guān)系型數(shù)據(jù)庫連接,下面這篇文章主要給大家介紹了關(guān)于MyBatis查詢數(shù)據(jù)庫語句的相關(guān)資料,文中通過實例代碼介紹的非常詳細(xì),需要的朋友可以參考下2023-06-06java?socket實現(xiàn)局域網(wǎng)聊天
這篇文章主要為大家詳細(xì)介紹了java?socket實現(xiàn)局域網(wǎng)聊天,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-05-05Java與Spring?boot后端項目Bug超全總結(jié)
Spring Boot是一個開源的 Java 開發(fā)框架,它的目的是簡化Spring應(yīng)用程序的開發(fā)和部署,下面這篇文章主要給大家介紹了關(guān)于Java與Spring?boot后端項目Bug的相關(guān)資料,文中通過圖文以及實例代碼介紹的非常詳細(xì),需要的朋友可以參考下2023-06-06