spring中bean的三种创建bean对象的方式:细节决定成败


/**
*账户的业务层实现类
*/

public class AccountServiceImpl implements IAccountService{
	
	public AccountServiceImpl(){
		System.out.println("对象创建了")}
	public void saveAccount(){
		System.out.println("service中的saveAccount方法执行了。。。“);
	}
}

在bean.xml页面中:

<!--把对象的创建交给spring来管理-->
	<!--spring对bean的管理细节
			1、创建bean的三种方式
			2、bean对象的作用范围
			3、bean对象的生命周期
	-->
	<!--创建bean的三种方式-->
	<!--第一种方式:使用默认构造函数创建。
				在spring的配置文件中使用bean标签,配以id和class属性之后,且没有					  其他属性和标签时。采用的就是默认构造函数创建bean对象,此时如果类中没有默认构造函数,则对象无法创建。
	-->
	<bean id="accountService" class="com.service.impl.AccountServiceImpl"></bean>



	<!--第二种方式:使用普通工厂中的方法创建对象(使用某个类中的方法创建对象,并存入spring容器)-->
	
	<bean id="instanceFactory" class="com.service.impl.AccountServiceImpl"></bean>

	<bean id="accountService" factory-bean="instanceFactory" factory-bean="instanceFactory" factory-method="getAccountService"></bean>
	
	<!--第三种方式:使用工厂中的静态方法创建(使用类中的静态方法创建对象,并存入spring容器)-->
	<bean id="accountService" class=“com.factory.StaticFactory” factory-method="getAccountService"></bean>
	

猜你喜欢

转载自blog.csdn.net/RacardoMlu/article/details/107771194