Spring如何通過注解引入外部資源(PropertySource?Value)
更新時間:2023年07月20日 09:05:51 作者:一只小小鳥
這篇文章主要為大家介紹了Spring通過注解@PropertySource和@Value引入外部資源的方法實現(xià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)的詳細內(nèi)容,更多關于Spring注解引入外部資源的資料請關注腳本之家其它相關文章!
相關文章
Mybatis輸入輸出映射及動態(tài)SQL Review
這篇文章主要介紹了Mybatis輸入輸出映射及動態(tài)SQL Review,需要的朋友可以參考下2017-02-02java?socket實現(xiàn)局域網(wǎng)聊天
這篇文章主要為大家詳細介紹了java?socket實現(xiàn)局域網(wǎng)聊天,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-05-05