DI---构造器注入


一、构造器注入

	<bean id="p" class="com.gql.entity.Person">
		<constructor-arg index="0" type="java.lang.String" value="冬雨"></constructor-arg>
		<constructor-arg index="1" type="java.lang.Integer" value="18"></constructor-arg>
	</bean>

成功通过构造器注入对象。
在这里插入图片描述

(1)测试依赖注入

package com.gql.di;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.gql.entity.Person;

/**
 * 类说明:
 *		测试依赖注入
 * @guoqianliang1998.
 */
public class Demo {
	@Test
	public void testConstructor(){
		ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
		Person p = (Person)ac.getBean("p");
		System.out.println(p.getName()+","+p.getAge());
	}
}

(2)Person实体类

在Person实体类中创建了有两个参数的Person构造函数

package com.gql.entity;

import java.util.ArrayList;
import java.util.List;

/**
 * 类说明: 
 * 		实体类Person 
 * @guoqianliang1998.
 */
public class Person {
	private String name;
	private Integer age;

	public Person() {
		super();
		// TODO Auto-generated constructor stub
	}

	public Person(String name, Integer age) {
		super();
		this.name = name;
		this.age = age;
	}
	
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Integer getAge() {
		return age;
	}

	public void setAge(Integer age) {
		this.age = age;
	}

	public void init() {
		System.out.println("初始化对象...");

	}

	public void destroy() {
		System.out.println("销毁对象...");
	}
}

(3)XML配置

applicationContext_Di.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="p" class="com.gql.entity.Person">
		<constructor-arg index="0" type="java.lang.String" value="冬雨"></constructor-arg>
		<constructor-arg index="1" type="java.lang.Integer" value="18"></constructor-arg>
	</bean>
</beans>

applicationContext.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">
	<import resource="com/gql/di/applicationContext_Di.xml"/>
</beans>
发布了362 篇原创文章 · 获赞 970 · 访问量 17万+

猜你喜欢

转载自blog.csdn.net/weixin_43691058/article/details/104094074