Spring如何通过注解引入外部资源(PropertySource Value)
作者:一只小小鸟
这篇文章主要为大家介绍了Spring通过注解@PropertySource和@Value引入外部资源的方法实现示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
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>那么如何利用注解来实现呢?
@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)的详细内容,更多关于Spring注解引入外部资源的资料请关注脚本之家其它相关文章!
