當前位置:
                    首頁 >
                            前端技术
>                            javascript
>内容正文                
                        
                    javascript
【Spring注解系列12】@Value与@PropertySource注解
                                                            生活随笔
收集整理的這篇文章主要介紹了
                                【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