1. 程式人生 > >通過Spring配置文件中bean中的property賦值

通過Spring配置文件中bean中的property賦值

pla 綁定 cli 原因 對象賦值 art contex start nbsp

基本數據類型賦值-通過spring配置文件中bean中的property

擴展-以此方式可以通過配置為連接數據的屬性賦值

1、如果是基本數據類型,可以通過setter方法為對象中的屬性設置初始值,應用:可以把以前寫dbc的東西寫進去

2、如果屬性的類型不是基本類型或String ,可以使用引用的方式為對象賦值(bean中property中的ref)

擴展-以此方式可以把數據庫的連接值給實現類賦值

3、集合屬性的賦值,註意要集合要初始化。基本數據類型不用初始化的原因就是它默認初始化(不常用)

4、通過構造方法為屬性賦值(不常用,一般都是使用setter方法賦值)

5、屬性自動綁定(不常用)

1)byName

2)byType

3)autodetect,先按ByName,再按ByType

舉例:

1.創建一個User類

[java] view plain copy print?
  1. public class User {
  2. private String userid;
  3. private String username;
  4. private int age;
  5. public int getAge() {
  6. return age;
  7. }
  8. public void setAge(int age) {
  9. this.age = age;
  10. }
  11. public String getUserid() {
  12. return userid;
  13. }
  14. public void setUserid(String userid) {
  15. this.userid = userid;
  16. }
  17. public String getUsername() {
  18. return username;
  19. }
  20. public void setUsername(String username) {
  21. this.username = username;
  22. }
  23. }

2.在配置文件中

[html] view plain copy print?
  1. <bean id="user" class="org.liky.spring.pojo.User">
  2. <!-- 可以通過屬性的setter方法為屬性初始化數據 -->
  3. <property name="userid" value="abc"></property>
  4. </bean>

3.測試程序

[java] view plain copy print?
    1. ApplicationContext context = new ClassPathXmlApplicationContext(
    2. "applicationContext.xml");
    3. User user = (User) context.getBean("user");
    4. System.out.println(user.getUserid());
    5. System.out.println(new User().getUserid());

通過Spring配置文件中bean中的property賦值