Spring Bean的实例化 构造方法实例化Bean

Spring Bean的实例化 构造方法实例化Bean,第1张

在面向对象程序中,如果要使用某个对象,就需要先实例化这个对象。同样地,在Spring中,要想使用容器中地Bean对象,也需要实例化Bean。

构造方法实例化

Spring容器通过Bean对应类中默认的无参构造方法来实例化Bean。

下面通过简单程序,来测试Bean1()无参构造方法是否可以实例化Bean1。 

 1.新建Maven项目,配置pom.xml文件

 

 具体代码:


    
        org.springframework
        spring-beans
        5.2.8.RELEASE
    
    
        org.springframework
        spring-beans
        5.2.8.RELEASE
    
    
        org.springframework
        spring-context
        5.2.8.RELEASE
    
    
        org.springframework
        spring-expression
        5.2.8.RELEASE
    
    
        commons-logging
        commons-logging
        1.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 {
  /*
  构造方法实例化Bean1:
  1.main()方法加载applicationBean1.xml配置文件初始化Spring容器
  2.通过Spring容器生成Bean1类的实例1
  3测试构造方法能否实例化Bean1
   */
    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的所有内容。 

 

 

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/800756.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-07
下一篇2022-05-07

发表评论

登录后才能评论

评论列表(0条)

    保存