天天看点

Spring创建对象的三种方法之一构造函数创建(源码)

Spring创建对象有三种方法,分别是:

1、构造函数创建

2、静态工厂方法

3、实例工厂方法

这里说下第一种方法,采用构造函数来创建,我这里直接给源码,凑合着看看,能用就可以了,如果想要更深入的了解,那么只有自己去找资料了。

第一个类:D1.java

package Gou;

public class D1 {

public void m(){//随便写的一个方法

System.out.println("spring 创建对象有三种:构造函数创建,静态工厂方法,实例工厂方法");

System.out.println("现在我是第一种,通过构造方法");

}

}

第二个类:D2.java

package Gou;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class D2 {

public static void main(String[] args) {

//装载单个配置文件,实例化ApplicationContext容器

ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");

D1 t=(D1)ac.getBean("d1");//得到ID为d1的这个类

t.m();//调用id为d1这个类里面的方法

}

}

xml文件: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-2.5.xsd">

<bean id="d1" class="Gou.D1"></bean>

<!-- id是自定义的,class是路径 -->

</beans>

这个还需要导入两个包,分别是:spring.jar和commons-logging.jar,我用的软件是Myeclipse。