栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

在面向对象程序中,如果要使用某个对象,就需要先实例化这个对象。同样地,在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 {
  
    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的所有内容。 

 

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/852212.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号