spring创建bean的方式

spring创建bean主要有三种方式

  • 默认的构造方法创建(常用)
  • 实例工厂创建
  • 静态工厂创建

 

方式一:(使用默认的构造方法)

实体类

 

package com.lzcc.instancefactorymethod;

/**
 * 数据访问对象层
 * @author
 *
 * @version v_1.00
 * 2014-4-20
 *
 * @author:
 * @updatetime:
 * @updatecontent:
 */
public class DAO {
	
	private String name;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
	
	public void add() {
		System.out.println(name + "的add方法在执行...");
	}

}

配置文件

 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       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">

       <bean id="student" class="com.lzcc.instancefactorymethod.DAO"></bean>

</beans>

方式二:(使用实例工厂创建)

实体类:

 

package com.lzcc.instancefactorymethod;

/**
 * 创建dao的工厂
 * @author
 * @version v_1.00
 * 2014-4-20
 *
 * @author:
 * @updatetime:
 * @updatecontent:
 */
public class DAOFactory {
	//实例化dao
	private DAO dao = new DAO();

	public DAOFactory() {
		super();
	}
	
	public DAO getDAO(){
		System.out.println("DAOFactory的getDAO方法执行了...");
		return dao;
	}

}

配置文件:

 

  <!-- 创建工厂的bean  -->        
 <bean id="daofactory" class="com.lzcc.instancefactorymethod.DAOFactory"></bean>
	
	<bean id="dao" factory-bean="daofactory" factory-method="getDAO">
	</bean>
	 
      <!-- 创建service层的bean  -->	
      <bean id="service" class="com.lzcc.instancefactorymethod.Service">
		<property name="dao" ref="dao"></property>
	 </bean>



方式三:(使用静态工厂创建)

 

public class ClientService {
  private static ClientService clientService = new ClientService();
  private ClientService() {}

  public static ClientService createInstance() {
    return clientService;
  }
}




配置文件

 

<bean id="clientService"
      class="examples.ClientService"
      factory-method="createInstance"/>

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值