一、无参构造函数创建                                                                           

我们用Spring创建Student类的对象

Student类声明如下

package com.study.spring;
public class Student {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "name:"+name+"\n"+"age:"+age;
} }

beans.xml配置如下

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="student" class="com.study.spring.Student">
<property name="name" value="尼古拉斯赵四"></property>
<property name="age" value="37"></property>
</bean>
</beans>

使用Bean工厂初始化,测试代码如下

package com.study.spring;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; public class Test {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("\\com\\study\\spring\\beans.xml");
Student stu = (Student) context.getBean("student");
System.out.println(stu); }
}

执行结果如下:

name:尼古拉斯赵四
age:37

总结

<bean id="student" class="com.study.spring.Student">
<property name="name" value="尼古拉斯赵四"></property>
<property name="age" value="37"></property>
</bean>

配置一个bean,id为代码中取得bean的代号,不可以重复,class为类的类型,包含完整的包名。property 指的是类中的属性 name为属性名称 ,value是给此属性赋的值。

值得注意的是,property 中的name属性的值对应的是类中属性的set方法,省略了前缀set,如本文中设置name=“age”实际上指的是给setAge方法传递一个参数的配置,所以命名应该按照约定,做到规范和命名。若没有set方法就无法实现实例化。直接报错。

最新文章

  1. sublime编辑器插件
  2. AFNetworking3.0使用
  3. jquery mobile 图片自适应问题
  4. SqlSever基础 datepart函数 返回现在多少秒
  5. volatile适用场景
  6. select,epoll的比较
  7. win8笔记本无法搜索wifi信号找不到WLAN该 wifi共享特别注意的服务
  8. Java IO - BufferedReader &amp; BufferedWriter
  9. JS 无提示关闭当前窗口
  10. Git简介及安装和简单配置
  11. Oracle job调用存储过程
  12. Python学习笔记3
  13. .Net 中通用的FormatString格式符整理
  14. 2019.03.28 bzoj3325: [Scoi2013]密码(manacher+模拟)
  15. mapper代理查询
  16. [代码]--给任意网站添加聊天功能,随时聊(fa)天(che)
  17. 将Integer赋值给int(空指针异常)
  18. 全国高校绿色计算大赛 预赛第一阶段(C++)第4关:计算日期
  19. javascript64位加密
  20. Clipboard.GetImage() Clipboard获取粘贴板内容为null的解决办法

热门文章

  1. Linux安全基础:配置network
  2. iOS之UIScrollView循环滚动
  3. Android开发学习——应用安装过程
  4. UIWindow
  5. sublime text 乱码生成.dump问题的解决方法
  6. Windows on Device 项目实践 4 - 智能风扇制作
  7. 基于ambari2.4.0进行二次开发
  8. 《java JDK7 学习笔记》之类和对象
  9. sql server: sql script
  10. Ubuntu搭建Ruby On Rail环境