Spring:xml类型进行值的注入

1.依赖注入之setter注入流程

(1)创建学生类Student(要提供setter方法)

public class Student {
	 private Integer id; 
	 private String name; 
	 private Integer age; 
	 private String sex; 
	 还有setter啥的方法不详细写了
  }

(2)配置bean时为属性赋值

<bean id="studentOne" class="com.atguigu.spring.bean.Student">
	 <!-- property标签:通过组件类的setXxx()方法给组件对象设置属性 --> 
	 <!-- name属性:指定属性名(这个属性名是getXxx()、setXxx()方法定义的,和成员变量无关) --> 
	 <!-- value属性:指定属性值 --> 
	   <property name="id" value="1001"></property>
	   <property name="name" value="张三"></property> 
	   <property name="age" value="23"></property>
	   <property name="sex" value="男">
	   </property> </bean>

(3)测试是否在容器中获取的到已经注入过值的对象。

@Test public void testDIBySet(){
 	 ApplicationContext ac = new ClassPathXmlApplicationContext("spring-di.xml");
 	 Student studentOne = ac.getBean("studentOne", Student.class); 
 	 System.out.println(studentOne); }
2.依赖注入之构造器注入

(1)在Student类中添加有参构造

public Student(Integer id, String name, Integer age, String sex) {
 this.id = id; 
 this.name = name; 
 this.age = age; 
 this.sex = sex; }

(2)配置bean

<bean id="studentTwo" class="com.atguigu.spring.bean.Student"> 
	<constructor-arg value="1002"></constructor-arg> 
	<constructor-arg value="李四"></constructor-arg> 
	<constructor-arg value="33"></constructor-arg> 
	<constructor-arg value="女"></constructor-arg> 
</bean>

(3)测试

@Test public void testDIBySet(){
	  ApplicationContext ac = new ClassPathXmlApplicationContext("spring-di.xml");
	  Student studentOne = ac.getBean("studentTwo", Student.class); 
	  System.out.println(studentOne); }

3.字面量赋值 4.为类类型属性赋值 4.1方式一 :引用外部已声明的bean 新建一个Clazz的类,然后它作为student的成员变量。 4.2方式二: 内部Bean 4.3方式三:级联属性赋值

5.为数组类型属性赋值

6.为集合类型属性赋值 7.为Map集合类型属性赋值

经验分享 程序员 微信小程序 职场和发展