当前位置:
首页 >
【Spring注解系列12】@Value与@PropertySource注解
发布时间:2025/3/20
58
豆豆
生活随笔
收集整理的这篇文章主要介绍了
【Spring注解系列12】@Value与@PropertySource注解
小编觉得挺不错的,现在分享给大家,帮大家做个参考.
1.@Value与@PropertySource注解
@Value注解:主要用于赋值,该值可以是取值配置文件中的,也可以直接赋值,也可以使用SpEl表达式进行计算的结果,抑或直接从环境变量中获取。 该注解不能处理日期类赋值
1、基本数值 2、可以写SpEL; #{} 3、可以写${};取出配置文件【properties】中的值(在运行环境变量里面的值)原理是底层使用了后置处理器AutowiredAnnotationBeanPostProcessor。
* <p>Note that actual processing of the {@code @Value} annotation is performed * by a {@link org.springframework.beans.factory.config.BeanPostProcessor * BeanPostProcessor} which in turn means that you <em>cannot</em> use * {@code @Value} within * {@link org.springframework.beans.factory.config.BeanPostProcessor * BeanPostProcessor} or * {@link org.springframework.beans.factory.config.BeanFactoryPostProcessor BeanFactoryPostProcessor} * types. Please consult the javadoc for the {@link AutowiredAnnotationBeanPostProcessor} * class (which, by default, checks for the presence of this annotation).
@PropertySource注解:主要用于加载配置文件,value值为classpath
等价于 <context:property-placeholder location="classpath:student.properties"/>
2.实例
@PropertySource放置的位置问题:
1.若使用@Component方式注入对象,则@PropertySource防止在普通类Student或配置类中都可以
2.若使用@Bean方式注入Student对象,则@PropertySource必须放在配置类上加载
方式一:使用@Component方式注入Student对象
/**** 使用@Value赋值;* 1、基本数值* 2、可以写SpEL; #{}* 3、可以写${};取出配置文件【properties】中的值(在运行环境变量里面的值)*/ @PropertySource({"classpath:/student.properties"})//指定配置文件classPath @Component //此时使用的是@Component方式注入,则@PropertySource放在哪都可以 public class Student {@Value("张三")//直接赋值private String name;@Value("${stu.name}")//从配置文件中取值private String alias;@Value("${os.name}")//从容器中读取环境变量private String system;@Value("#{33-12}")//使用SpEL 计算private Integer age; // @Value("${stu.birthDate}")//不能处理日期private Date birthDate;@Value("${stu.hasNickName}") //布尔值private Boolean hasNickName;@Overridepublic String toString() {return "Student{" +"name='" + name + '\'' +", alias='" + alias + '\'' +", system='" + system + '\'' +", age=" + age +", birthDate=" + birthDate +", hasNickName=" + hasNickName +'}';}public Boolean getHasNickName() {return hasNickName;}public void setHasNickName(Boolean hasNickName) {this.hasNickName = hasNickName;}public String getAlias() {return alias;}public void setAlias(String alias) {this.alias = alias;}public String getSystem() {return system;}public void setSystem(String system) {this.system = system;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}public Date getBirthDate() {return birthDate;}public void setBirthDate(Date birthDate) {this.birthDate = birthDate;} }@Configuration @ComponentScan(basePackages = "com.java.model") //@PropertySource({"classpath:/student.properties"}) //放在这里也可以 public class PropertyValueConfig {}public class PropertyValueTest {public static void main(String[] args) {AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(PropertyValueConfig.class);Student s = applicationContext.getBean(Student.class);System.out.println(s);} }测试结果: Student{name='张三', alias='张三', system='Windows 7', age=21, birthDate=null, hasNickName=true}方式二:使用@Bean方式注入Student对象
/**** 使用@Value赋值;* 1、基本数值* 2、可以写SpEL; #{}* 3、可以写${};取出配置文件【properties】中的值(在运行环境变量里面的值)*/ public class Student {@Value("张三")//直接赋值private String name;@Value("${stu.name}")//从配置文件中取值private String alias;@Value("${os.name}")//从容器中读取环境变量private String system;@Value("#{33-12}")//使用SpEL 计算private Integer age; // @Value("${stu.birthDate}")//不能处理日期private Date birthDate;@Value("${stu.hasNickName}") //布尔值private Boolean hasNickName;@Overridepublic String toString() {return "Student{" +"name='" + name + '\'' +", alias='" + alias + '\'' +", system='" + system + '\'' +", age=" + age +", birthDate=" + birthDate +", hasNickName=" + hasNickName +'}';}public Boolean getHasNickName() {return hasNickName;}public void setHasNickName(Boolean hasNickName) {this.hasNickName = hasNickName;}public String getAlias() {return alias;}public void setAlias(String alias) {this.alias = alias;}public String getSystem() {return system;}public void setSystem(String system) {this.system = system;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}public Date getBirthDate() {return birthDate;}public void setBirthDate(Date birthDate) {this.birthDate = birthDate;} }@Configuration @PropertySource({"classpath:/student.properties"}) //此时只能放在这里加载 public class PropertyValueConfig {@Beanpublic Student student(){return new Student();} }public class PropertyValueTest {public static void main(String[] args) {AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(PropertyValueConfig.class);Student s = applicationContext.getBean(Student.class);System.out.println(s);} }测试结果: Student{name='张三', alias='张三', system='Windows 7', age=21, birthDate=null, hasNickName=true}
3.EmbeddedValueResolverAware方式实现和@Value一样的效果
EmbeddedValueResolverAware是一个String型的value解析器,想要通过这个获取值的任何对象,都可以实现这个接口。
/*** Interface to be implemented by any object that wishes to be notified of a* {@code StringValueResolver} for the resolution of embedded definition values.** <p>This is an alternative to a full ConfigurableBeanFactory dependency via the* {@code ApplicationContextAware}/{@code BeanFactoryAware} interfaces.** @author Juergen Hoeller* @author Chris Beams* @since 3.0.3* @see org.springframework.beans.factory.config.ConfigurableBeanFactory#resolveEmbeddedValue(String)* @see org.springframework.beans.factory.config.ConfigurableBeanFactory#getBeanExpressionResolver()* @see org.springframework.beans.factory.config.EmbeddedValueResolver*/ public interface EmbeddedValueResolverAware extends Aware {/*** Set the StringValueResolver to use for resolving embedded definition values.*/void setEmbeddedValueResolver(StringValueResolver resolver);}
使用方法如下:
@Configuration //@ComponentScan(basePackages = "com.java.model") @PropertySource({"classpath:/student.properties"})//指定配置文件classPath public class PropertyValueConfig implements EmbeddedValueResolverAware{@Beanpublic Student student(){System.out.println("EmbeddedValueResolverAware----->setEmbeddedValueResolver--->stu = "+stuName);return new Student();}private String stuName;@Overridepublic void setEmbeddedValueResolver(StringValueResolver resolver) {this.stuName = resolver.resolveStringValue("${stu.name}");} }
总结
以上是生活随笔为你收集整理的【Spring注解系列12】@Value与@PropertySource注解的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: 【Spring注解系列11】Spring
- 下一篇: 【Spring注解系列13】Spring