本文共 1607 字,大约阅读时间需要 5 分钟。
创建一个Student类:
package domain;public class Student { private String username; private String password; private int age; public Student(String username, String password) { this.username = username; this.password = password; } public Student(String username, int age) { this.username = username; this.age = age; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "Student{" + "username='" + username + '\'' + ", password='" + password + '\'' + ", age=" + age + '}'; }}
beans.xml文件的配置如下:
注意在写参数时要保证有对应的构造方法否则报错
。
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");Student student = (Student) context.getBean("student");System.out.println(student);另外一种方式时通过索引来配置参数:
表示调用public Student(String username, int age)
,注意上面的int
不可以写成java.lang.Integer
,Spring不会自动转化,如果这样写会报错。
关于property标签,其实就是利用setter方法来赋值,这个在前面的章节已经演示过了,这里不做演示。我们来看看p命名空间
的参数注入方式。
运行测试代码如下:
转载地址:http://ttlzi.baihongyu.com/