Spring IOC容器创建对象的方式

时间:2024-04-08 13:03:14

一、无参构造函数创建                                                                           

我们用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方法就无法实现实例化。直接报错。

相关文章