一、构造方法实例化

下面通过一个案例演示Spring容器如何通过构造方法实例化Bean。 

(1)、在IDEA中创建一个名为chapter07的Maven项目,然后在项目的pom.xml文件中配置需使用到的Spring四个基础包和Spring的依赖包。

org.springframework

spring-core

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

org.springframework

spring-aop

5.2.8.RELEASE

(2)、创建一个名称为com.mac的包,在该包中创建Bean1类。 

package com.mac;

public class Bean1 {

public Bean1(){

System.out.println("这是Bean1");

}

}

(3)、新建applicationBean1.xml作为Bean1类的配置文件,在该配置文件中定义一个id为bean1的Bean,并通过class属性指定其对应的实现类为Bean1。 

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">

(4)、创建测试类Bean1Test,在main()方法中通过加载applicationBean1.xml配置文件初始化Spring容器,再通过Spring容器生成Bean1类的实例bean1,用来测试构造方法是否能实例化Bean1。

public class Bean1Test {

public static void main(String[] args){

// 加载applicationBean1.xml配置

ApplicationContext applicationContext=new

ClassPathXmlApplicationContext("applicationBean1.xml");

// 通过容器获取配置中bean1的实例

Bean1 bean=(Bean1) applicationContext.getBean("bean1");

System.out.print(bean); }

}

(5)、 在IDEA中启动Bean1Test类,控制台会输出结果。

二、 静态工厂实例化 

下面通过一个案例演示如何使用静态工厂方式实例化Bean。

(1)、创建Bean2类,该类与Bean1类一样,只定义一个构造方法,不需额外添加任何方法。

package com.mac;

public class Bean2 {

public Bean2(){

System.out.println("这是Bean2");

}

}

 (2)、创建一个MyBean2Factory类,在该类中定义一个静态方法createBean(),用于创建Bean的实例。createBean()方法返回Bean2实例。

package com.mac;

public class MyBean2Factory {

//使用MyBean2Factory类的工厂创建Bean2实例

public static Bean2 createBean(){

return new Bean2();

}

}

(3)、新建applicationBean2.xml文件,作为MyBean2Factory类的配置文件。 

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-4.3.xsd">

class="com.mac.MyBean2Factory"

factory-method="createBean"/>

(4)、创建一个测试类Bean2Test,用于测试使用静态工厂方式是否能实例化Bean。 

public class Bean2Test {

public static void main(String[] args) {

// ApplicationContext在加载配置文件时,对Bean进行实例化

ApplicationContext applicationContext =

new ClassPathXmlApplicationContext("applicationBean2.xml");

System.out.println(applicationContext.getBean("bean2"));

}

}

 (5)、在IDEA中启动Bean2Test类,控制台会输出结果。

参考阅读

评论可见,请评论后查看内容,谢谢!!!
 您阅读本篇文章共花了: