Spring IOC 创建bean实例的方式

据我所知,创建bean实例的方式有4种方式~

下面我会一一写出来这4种方式~

第一种:xml文件中有bean的配置,而且这个bean所对应的java类中存在一个无参构造器,那么这个时候spring容器就可以使用反射调用无参构造器来创建实例了~

代码如下:

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

	xmlns:context="http://www.springframework.org/schema/context"

	xsi:schemaLocation="http://www.springframework.org/schema/beans

           http://www.springframework.org/schema/beans/spring-beans-3.2.xsd

           http://www.springframework.org/schema/context

           http://www.springframework.org/schema/context/spring-context-3.2.xsd">
  <bean name="stu" class="com.x.spring.test1.Student">
      <property name="name">
          <value>张三</value>
      </property>
  </bean>

</beans>

这就是一个bean实例~,我前几篇就是这样创建bean实例的,我这里就不多说了~接下来看第二种方式

第二种:通过工厂类获得实例(工厂类实现了接口FactoryBean<?>)

注意:spring中的PropertyPlaceholderConfigurer类的使用,在htmlsingle中直接搜索类名即可

例如:

工厂类ConnectionFactory实现指定接口并且实现接口中的三个抽象方法:

public class ConnectionFactory implements FactoryBean<Connection>{

	private String driver;
	private String url;
	private String username;
	private String password;

	public String getDriver() {
		return driver;
	}

	public void setDriver(String driver) {
		this.driver = driver;
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

    //连接
	@Override
	public Connection getObject() throws Exception {
		Class.forName(driver);
		Connection conn =
			DriverManager.getConnection(url,username,password);
		return conn;
	}

	@Override
	public boolean isSingleton() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public Class<Connection> getObjectType() {
		// TODO Auto-generated method stub
		return Connection.class;
	}
}

注意:一定要加上这个jar包-mysql-connector-java-5.1.18-bin.jar,这个jar包我在Hibernate里面就用过,这是连接数据库的~如图:

配置文件factory.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-2.5.xsd">

	<!-- 通过conn拿到的是对应的这个工厂类所生产的产品对象 -->
	<!-- 造成这种现象的原因:因为这个类ConnectionFactory是一个工厂类,所以我们用名字conn在容器中拿对象的时候,
    	拿到并不是这个工厂类对象,而是这个工厂类对象调用完工厂方法后所返回的对象. -->
	<bean name="conn" class="com.x.spring.test3.factory.ConnectionFactory">
	    <!-- 从一个配置文件中以key—value的形式拿value -->
		<property name="url" value="${url}"></property>
		<property name="driver" value="${driver}"></property>
		<property name="username" value="${username}"></property>
		<property name="password" value="${password}"></property>
	</bean>

     <!--
    	下面配置的这个类,可以自动的帮我们去读取指定的properties文件的
    	内容,文件中用key-value的形式存放数据,读完之后我们就可以用
    	${key}这种形式去拿文件中的value值了。
    	classpath指的是从src下面找.
      -->
	<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
	  <property name="locations" value="classpath:mysql.properties"/>
	</bean>
</beans>

还需要properties文件~我放在src目录下面~

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/ssh
username=root
password=root

测试类FactoryTest:

public class FactoryTest {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		//在xml中配置工厂类,然后通过这个工厂类获得工厂生产的实例
		try {
			String path = "com/x/spring/test3/factory/factory.xml";
			ApplicationContext container =
					new ClassPathXmlApplicationContext(path);
			Connection conn = (Connection)container.getBean("conn");
			System.out.println(conn);
			conn.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}

效果图:

注意: 通过conn拿到的并不是要拿到工厂类的对象,而是对应的这个工厂类所生产的产品对象~这一点要记住

好了,第二种方式写完了,开始第三种方式~

第三种:通过实例工厂获得实例(不需要实现或者继承任何接口或者父类)

注意spring中的PropertyPlaceholderConfigurer类的使用,在htmlsingle中直接搜索类名即可

例如:

一个普通的工程类ConnectionFactory:

public class ConnectionFactory {

	private String driver;
	private String url;
	private String username;
	private String password;

	public Object getConnection() throws Exception {
		Class.forName(driver);
		Connection conn =
			DriverManager.getConnection(url,username,password);
		return conn;
	}
	public String getDriver() {
		return driver;
	}

	public void setDriver(String driver) {
		this.driver = driver;
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}
}

这个类没有继承和实现任何接口或类

配置文件instanceFactory.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-3.2.xsd">
   <span style="color:#ff0000;"><!-- 读取properties文件 --></span>
	<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="locations" value="classpath:mysql.properties"/>
	</bean>

    <bean name="factory" class="com.x.spring.test3.instanceFactory.ConnectionFactory">
   		<property name="url" value="${url}"></property>
		<property name="driver" value="${driver}"></property>
		<property name="username" value="${username}"></property>
		<property name="password" value="${password}"></property>
    </bean>

    <span style="color:#ff0000;"> <!--
		将来通过这个conn来拿对象,拿到的是名字为factory的工厂类调用完
		名字为getConnection方法之后所返回的对象。
	 --></span>
    <bean name="conn" factory-bean="factory" factory-method="getConnection"></bean>

</beans>

properties文件上面有代码,我就不贴了~

测试类InstanceTest:

public class InstanceTest {

	public static void main(String[] args) {
		//通过实例工厂获得实例(不需要实现或者继承任何接口或者父类)
		try {
			String path = "com/x/spring/test3/instanceFactory/instanceFactory.xml";
			ApplicationContext container =
					new ClassPathXmlApplicationContext(path);
			Connection conn = (Connection)container.getBean("conn");
			System.out.println(conn);
			conn.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

效果图:

好了,第三种方式也说完了~接下来第四种~

第四种:通过静态工厂获得实例

例如:含义静态方法的工厂类ConnectionFactory

public class ConnectionFactory {
	private static String driver = "com.mysql.jdbc.Driver";
	private static String url = "jdbc:mysql://localhost:3306/ssh";
	private static String username = "root";
	private static String password = "root";

	public static Object getConnection() throws Exception {
		Class.forName(driver);
		Connection conn =
			DriverManager.getConnection(url,username,password);
		return conn;
	}
}

有没有觉得这个很熟悉~不错,这就是properties文件的一些配置属性~

这就可以不用写properties文件了~

配置文件staticFactory.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-3.2.xsd">
     <!-- 这样配置一定要求getConnection方法是静态方法 -->
    <bean name="conn" class="com.x.spring.test3.staticFactory.ConnectionFactory" factory-method="getConnection"></bean>

</beans>

测试类:

public class StaticTest {

	public static void main(String[] args) {
		//通过静态工厂获得实例
		try {
			String path = "com/x/spring/test3/staticFactory/staticFactory.xml";
			ApplicationContext container =
					new ClassPathXmlApplicationContext(path);
			Connection conn = (Connection)container.getBean("conn");
			System.out.println(conn);
			conn.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

运行效果:

有没有觉得这三种方式的效果图都差不多~

就后面的一些数字不一样~

看来这三种方式通过conn拿到的并不是要拿到工厂类的对象,而是对应的这个工厂类所生产的产品对象~这一点要记住

时间: 2024-08-30 00:04:45

Spring IOC 创建bean实例的方式的相关文章

Spring框架笔记(十一)——IOC容器创建bean实例的第三种方法——FactoryBean

IOC容器创建bean实例有3类方法: 1 通过bean对应实例的全类名 2 通过工厂方法,包括静态工厂和实例工厂 3 实现 FactoryBean 接口在 Spring IOC 容器中配置 Bean 今天我们介绍这第三种方法--FactoryBean Spring 中有两种类型的 Bean, 一种是普通Bean, 另一种是工厂Bean, 即FactoryBean. 工厂 Bean 跟普通Bean不同, 其返回的对象不是指定类的一个实例, 其返回的是该工厂 Bean 的 getObject 方法

使用反射创建Bean、Spring中是如何根据类名配置创建Bean实例、Java提供了Class类获取类别的字段和方法,包括构造方法

Java提供了Class类,可以通过编程方式获取类别的字段和方法,包括构造方法 获取Class类实例的方法: 类名.class 实例名.getClass() Class.forName(className) public class RefTest { @Test public void testRef(){ //Class cls = RefTest.class; //Class.forName("com.jboa.service.RefTest"); //new RefTest()

(001)spring容器创建bean的两种方式

简单记录一下spring容器创建.装配.管理bean 1.使用@Configuration.@Bean的注解组合创建bean 可以用两种方法获取bean,根据类名或者创建bean的方法名,如果不指定bean的名字,默认bean的名字是该方法名. pom.xml文件如下: <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.

spring中创建bean对象的三种方式以及作用范围

时间:2020/02/02 一.在spring的xml配置文件中创建bean对象的三种方式: 1.使用默认构造函数创建.在spring的配置文件中使用bean标签,配以id和class属性之后,且没有其他属性和标签时采用的就是默认构造函数创建bean对象,此时如果类中没有默认构造函数函数,则对象无法创建. <bean id="one" class="sdnu.machi.one"></bean> 如果one.class中没有默认构造函数则会报

Spring学习(二)spring ioc注入的三种方式

一.spring ioc注入有哪三种方式: a setter 原理 : 在目标对象中,定义需要注入的依赖对象对应的属性和setter方法:"让ioc容器调用该setter方法",将ioc容器实例化的依赖对象通过setter注入给目标对象,封装在目标对象的属性中. b 构造器 原理 : 为目标对象提供一个构造方法,在构造方法中添加一个依赖对象对应的参数.ioc容器解析时,实例化目标对象时会自动调用构造方法,ioc只需要为构造器中的参数进行赋值:将ioc实例化的依赖对象作为构造器的参数传入

Spring IOC的三种注入方式

Spring IOC三种注入方式: 1.    接口注入 2.    getter,setter方式注入 3.    构造器注入 对象与对象之间的关系可以简单的理解为对象之间的依赖关系:A类需要B类的一个实例来进行某些操作,比如在A类的方法中需要调用B类的方法来完成功能,叫做A类依赖于B类.控制反转是一种将组件依赖关系的创建和管理置于程序外部的技术,由容器控制程序之间的关系,而不是由代码直接控制. 1.接口注入 public class ClassA {  private InterfaceB

mvn中,使用spring中获取bean实例

由于spring官方的例子都是用maven进行代码管理, 我打算以后的代码也用maven进行管理. spring一个重要的优点就是Ioc,也就是控制反转,可以用xml文件来生成类的实例.我以前都是用eclipse下的tomcat方式来管理bean实例,用spring自带的spring tool suits管理还有点不习惯,不过生产工具都是不断优化的,所以这里也学着习惯使用. 配置文件可以放在resources文件夹下,具体目录为src\main\resources,src下的另一个文件是java

Spring 简化装配Bean的配置方式

简化配置方式 Spring 为字面值.引用 Bean 和集合都提供了简化的配置方式.如果没有用到完整配置格式的特殊功能,用户大可使用简化的配置方式.下面分别为上面提及的配置内容给出简化前和简化后的版本. 1.字面值属性   简化前 简化后 字面值属性 <property name="maxSpeed"> <value>200</value></property> <property name="maxSpeed"

通过工厂方法创建bean实例

1.静态工厂方法 /** * 静态工厂方法:直接调用某一个类的静态方法就可以返回bean实例 *  * */ 1)先建立静态工厂public class StaticCarFactory { private static Map<String,Car> cars = new HashMap<String,Car>(); static { cars.put("audi", new Car("audi",300000)); cars.put(&q