欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Spring框架_实例化Bean的三种方式

程序员文章站 2022-05-24 18:23:10
...

 在使用Spring的时候,Spring给我们提供了三种实例化bean的方式。

1. 构造方法实例化(默认无参数)
 <1>创建一个对象类,提供一个无参构造。

 <2>在spring的配置文件中进行配置(比如:applicationContext.xml)

配置情况如下:

<!-- 默认情况下使用的就是无参数的构造方法. -->
<bean name="demo" class="demo的全路径"></bean>

 <3>使用getBean( )方法创建

// 无参数的构造方法的实例化
public void test() {
    ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
        "applicationContext.xml");
    Demo demo = (Demo) applicationContext.getBean("demo");
    System.out.println(demo);
}


2. 静态工厂实例化
 <1>创建对象类以及对象工厂类

//对象类
public class Demo{

}


//对象静态工厂类
public class DemoFactory{
    public static Demo getDemo(){
        return new Demo();
    }
}

 <2>在spring配置文件中进行配置(比如:applicationContext.xml),
配置如下:

<!-- 第二种使用静态工厂实例化 -->
<bean id="demo" class="Dome静态工厂的全类名"
        factory-method="创建demo的方法(getDemo)">
</bean>

 <3>使用getBean( )方法

// 静态工厂实例化
public void test() {
    ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
        "applicationContext.xml");
    Demo demo = (Demo) applicationContext.getBean("demo");
    System.out.println(demo);
}

3. 实例工厂实例化
 <1>创建对象类和对象实例工厂

//对象类
public class Demo{

}


//对象工厂类
public class DemoFactory{
    public Demo getDemo(){
        return new Demo();
    }
}

 <2>在spring的配置文件下进行配置(例如:applicationContext.xml),
配置如下:

<!-- 第三种使用实例工厂实例化 -->
<bean id="demo" factory-bean="demoFactory" factory-method="getDemo"></bean>
<bean id="demoFactory" class="Demo实例工厂的全类名"></bean>

 <3>使用getBean( )方法

// 实例工厂实例化
public void test() {
    ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
        "applicationContext.xml");
    Demo demo= (Demo) applicationContext.getBean("demo");
    System.out.println(demo);
}