Been1 类
package com.student.instance.constructor;
public class Bean1 {
}
Bean1.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">
<!-- services -->
<bean id="bean1" class="com.student.instance.constructor.Bean1">
</bean>
</beans>
instanceTest1测试类
package com.student.instance.constructor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class instanceTest1 {
public static void main(String[] args) {
String xmlPath = "com/student/instance/constructor/Bean1.xml";
ApplicationContext applicationContext =new ClassPathXmlApplicationContext(xmlPath);
Bean1 bean =(Bean1)applicationContext.getBean("bean1");
System.out.println(bean);
}
}
解释:在加载配置文件的时候,Spring容器(ApplicationContext)会通过Bean1(实现类)或者说被调用的类的无参构造方法,对Bean进行实例化。也就是说,加载配置文件的同时,被调用的类通过自己的无参构造方法,把自己交给了Bean(Spring容器)。
运行结果:
十月 13, 2019 2:11:44 下午 org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@46f7f36a: startup date [Sun Oct 13 14:11:44 CST 2019]; root of context hierarchy
十月 13, 2019 2:11:44 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [com/student/instance/constructor/Bean1.xml]
com.student.instance.constructor.Bean1@6a024a67
浙公网安备 33010602011771号