通過Spring配置文件中bean中的property賦值
阿新 • • 發佈:2017-08-10
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?
- public class User {
- private String userid;
- private String username;
- private int age;
- public int getAge() {
- return age;
- }
- public void setAge(int age) {
- this.age = age;
- }
- public String getUserid() {
- return userid;
- }
- public void setUserid(String userid) {
- this.userid = userid;
- }
- public String getUsername() {
- return username;
- }
- public void setUsername(String username) {
- this.username = username;
- }
- }
2.在配置文件中
[html] view plain copy print?
- <bean id="user" class="org.liky.spring.pojo.User">
- <!-- 可以通過屬性的setter方法為屬性初始化數據 -->
- <property name="userid" value="abc"></property>
- </bean>
3.測試程序
[java] view plain copy print?
- ApplicationContext context = new ClassPathXmlApplicationContext(
- "applicationContext.xml");
- User user = (User) context.getBean("user");
- System.out.println(user.getUserid());
- System.out.println(new User().getUserid());
通過Spring配置文件中bean中的property賦值