1.Set注入
<bean id="myStudent" class="com.dwk.ba02.Student">
<property name="name" value="李四"/>
<property name="age" value="20"/>
<!--引用类型-->
<property name="school" ref="mySchool"/>
</bean>
<!--声明School对象-->
<bean id="mySchool" class="com.dwk.ba02.School">
<property name="name" value="西安邮电"/>
<property name="address" value="雁塔区"/>
</bean>
@Test
public void test02(){
System.out.println("====test02=====");
String config="ba02/applicationContext.xml";
ApplicationContext ac=new ClassPathXmlApplicationContext(config);
Student myStudent= (Student) ac.getBean("myStudent");
System.out.println("student对象="+myStudent);
}
2.构造注入
<!--
使用name属性实现构造注入
-->
<bean id="myStudent" class="com.dwk.ba03.Student">
<constructor-arg name="myname" value="张三"/>
<constructor-arg name="myage" value="20"/>
<constructor-arg name="mySchool" ref="myXueXiao"/>
</bean>
<!--使用index属性-->
<bean id="myStudent2" class="com.dwk.ba03.Student">
<constructor-arg index="0" value="李四"/>
<constructor-arg index="1" value="20"/>
<constructor-arg index="2" ref="myXueXiao"/>
</bean>
<!--使用index属性,按照顺序可以省略index-->
<bean id="myStudent3" class="com.dwk.ba03.Student">
<constructor-arg value="王五"/>
<constructor-arg value="25"/>
<constructor-arg ref="myXueXiao"/>
</bean>
<!--声明School对象-->
<bean id="myXueXiao" class="com.dwk.ba03.School">
<property name="name" value="西安邮电"/>
<property name="address" value="雁塔区"/>
</bean>
@Test
public void test01(){
String config="ba03/applicationContext.xml";
ApplicationContext ac=new ClassPathXmlApplicationContext(config);
//从容器中获取Student对象
Student myStudent= (Student) ac.getBean("myStudent3");
System.out.println("student对象="+myStudent);
File myfile= (File) ac.getBean("myfile");
System.out.println("myfile=="+myfile.getName());
}
3.如何使用Spring
1)在pom中创建依赖:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
2)创建类,可以有接口也可以没有
3)创建spring的配置文件,使用声明对象
4)我们使用容器中的对象,是通过:ApplicationContext接口和他的实现类ClassPathXmlApplicationContext的方法getBean()