springIOC
1.springIOC 即控制反转,不用spring之前,创建一个对象需要自己new,用spring之后,只需在配置文件中配置。
1)对象的属性注入
- 类中有空的构造方法。使用<property name ="",value=""/>
- 类中有有参数的构造方法。
<constructor-arg name="" value=""></constructor-arg>
2)scope属性,默认singleton—单例模式,获取的是同一个对象。prototype----表示通过spring获取的对象不同。如:<bean id=’’ class=’'scope=‘singleton’>
3)parent属性,使用parent属性,可以继承类中的属性。还可以覆盖属性值。
public class Student{
private int id;
private String name;
private int age;
}
spring.xml配置文件
<bean id ="student" class="com.Student">
<property name ="id",value="1"/>
<property name ="name",value="张三"/>
<property name ="age",value="23"/>
</bean>
<bean id ="student1" class="com.Student" parent='student'>
</bean>
输出打印student和student1,两个一样的值:id=1,name=张三,age=23。
注:输出是创建测试类,获取Spring容器,可通过id和运行时获取对象,然后打印:
ApplicationContext applicationContext = new ClassPathXmlApplicationContext('spring.xml');
//2.通过运行时类获取对象
Student stu = applicationContext.getBean(Student.class);//运行时获取。
//Student stu = applicationContext.getBean("student");通过id获取,student为beanId;
System.out.println(stu);
<bean id ="student" class="com.Student">
<property name ="id",value="1"/>
<property name ="name",value="张三"/>
<property name ="age",value="23"/>
</bean>
<bean id ="student1" class="com.Student" parent='student'>
<property name ="name",value="李四"/>
</bean>
这样可以覆盖,上面属性中的名字,输出student1对象则输出:id=1,name=李四,age=23.
4)P命名空间,属性注入,简化方法,
2.DI 依赖注入,在spring配置文件中,通过ref属性将其他bean赋给当前bean对象,是IOC的具体实现方式。
例如:
public class Classes{
private int id;
private student stu1;
public classes(){
}
}
public class Student{
private int id;
private String name;
private int age;
}
spring.xml中配置
<bean id ="class" class="com.Classes">
<property name ="id",value="1"/>
<property name ="stu1",ref="student"/>
</bean>
<bean id ="student" class="com.Student">
<property name ="id",value="1"/>
<property name ="name",value="张三"/>
<property name ="age",value="23"/>
</bean>