在面向对象程序中,如果要使用某个对象,就需要先实例化这个对象。同样地,在Spring中,要想使用容器中地Bean对象,也需要实例化Bean。
构造方法实例化
Spring容器通过Bean对应类中默认的无参构造方法来实例化Bean。
下面通过简单程序,来测试Bean1()无参构造方法是否可以实例化Bean1。
1.新建Maven项目,配置pom.xml文件
具体代码:
org.springframework spring-beans5.2.8.RELEASE org.springframework spring-beans5.2.8.RELEASE org.springframework spring-context5.2.8.RELEASE org.springframework spring-expression5.2.8.RELEASE commons-logging commons-logging1.2
2.新建Bean1.java
具体代码:
package com.itheima; public class Bean1 { //Bean1()无参构造方法 public Bean1(){ System.out.println("Bean1"); } }
3.新建application.xml文件
具体代码:
4.新建Bean1Test.java
具体代码:
package com.itheima.Test; import com.itheima.Bean1; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Bean1Test { public static void main(String[] args) { //ClassPathXmlApplicationContext实现类从类路径加载配置文件,实例化ApplicationContext接口 ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationBean1.xml"); //通过容器获取配置中Bean1中的实例 Bean1 bean1=(Bean1) applicationContext.getBean("bean1"); System.out.println(bean1); } }
运行结果:
以上就是测试构造方法能否实例化Bean的所有内容。



