本篇內容介紹了“Spring中如何實現給Bean屬性賦值”的有關知識,在實際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領大家學習一下如何處理這些情況吧!希望大家仔細閱讀,能夠學有所成!
屬性賦值
@Value注解的定義:
測試
1.在添加了Spring依賴的Maven項目中創建
2.在resources目錄下創建一個配置文件person.properties
3.創建配置類
4.創建測試類進行測試
5.測試結果:
如何給Bean的屬性賦值(注入)
1.通過構造方法設置值。
2.設置注入(通過set方法)
只用Spring注解開發的時候,可以使用@Value搭配@PropertySource注解進行給Bean的屬性進行賦值。
@Value
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface Value { /** * The actual value expression: for example {@code #{systemProperties.myProp}}. */ String value(); }
可以看到@Value注解接受的參數只能是字符串,所以使用時參數都需要帶上雙引號。并且可以在屬性,方法,參數等位置上標注。value屬性支持以下三種類型:
基本數據類型,包括String,int,boolean等類型。
SpEL,#{}的形式即表示使用SpEL表達式,一般用于獲取環境中其他bean的屬性,當使用Elivis運算符“表達式1?:表達式2”,比如#{ “obj.property? :default_value” }形式時,這里的obj是取當前容器中的對象,default_value就是前面的值為空時的默認值。
在主配置類中通過@PropertySource注解加載配置文件,然后通過${ property : default_value}的形式取配置文件中的值,其中default_value表示前面的值為空時的默認值。
以下兩個實體類Student類和Teacher類
public class Teacher { public int id; public String name; public Teacher() { // TODO Auto-generated constructor stub System.out.println("teacher-----創建"); } public Teacher(int id, String name) { super(); this.id = id; this.name = name; } //省略getter和setter方法 }
在Student類中使用${}取配置文件的值,#{}取容器中的teacher對象的name屬性
public class Student{ @Value("1") private int id; @Value("${student.name}") private String name; @Value("${student.address:北京}") private String address; @Value("#{teacher.name?:'老子'}") private String teacherName; @Override public String toString() { return "Student [id=" + id + ", name=" + name + ", address=" + address + ", teacherName=" + teacherName + "]"; } //省略getter和setter方法 }
添加以下值:
student.name=張三 person.address=廣州市
使用@PropertySource注解讀取外部配置文件person.properties中的key/value保存到運行的環境變量中。
@Configuration @PropertySource("person.properties") public class SpringConfig2 { @Bean public Student student() { return new Student(); } @Bean public Teacher teacher() { return new Teacher(2,"老李"); } }
編寫代碼獲取容器中的id為student的bean和直接獲取配置環境的屬性值。
public class IoCTest { @Test public void test() { //獲取Spring的IOC容器 AnnotationConfigApplicationContext applicationContext=new AnnotationConfigApplicationContext(SpringConfig2.class); //從容器中獲取bean Student stu = (Student) applicationContext.getBean("student"); System.out.println(stu); //獲取環境變量 ConfigurableEnvironment environment = applicationContext.getEnvironment(); String property = environment.getProperty("person.address"); System.out.println(property); //關閉容器 applicationContext.close(); } }
通過property標簽(內部是通過調用類的set方法將值注入)
“Spring中如何實現給Bean屬性賦值”的內容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業相關的知識可以關注億速云網站,小編將為大家輸出更多高質量的實用文章!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。