了解bean对象

目录

1、bean对象的三种创建方式

1)通过调用构造函数创建:

2)通过静态工厂创建bean对象

3)通过实例工厂创建对象

2、bean对象的作用范围

3、bean对象的生命周期


1、bean对象的三种创建方式

1)通过调用构造函数创建:

        在默认情况下,准备好配置文件后,spring就会调用默认构造函数创建对象,如果不存在默认构造函数,则创建失败,如下图:

2)通过静态工厂创建bean对象

        bean.xml:

<!-- 静态工厂创建 -->
    <bean id="staticaccountService" class="factory.StaticBeanFactory" factory-method="getBean"></bean>

       StaticBeanFactory:

package factory;

import rumen.AccountServiceImpl;
import rumen.IAccountService;

public class StaticBeanFactory {
	
	public static IAccountService getBean() {
		return new AccountServiceImpl(); 
	}
}

     Client:

package rumen;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

//表现层
public class Client {

	//获取Spring的核心容器,并根据id获取对象
	public static void main(String[] args) throws ClassNotFoundException {
		//1.获取Spring的核心容器
		ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
		//2.根据id获取对象
		IAccountService as = (IAccountService) ac.getBean("staticaccountService");
		
		System.out.println(as);

	}

}

3)通过实例工厂创建对象

bean.xml:

<!-- 实例工厂创建 -->
    <bean id="instanceFactory" class="factory.InstanceBeanFactory"></bean>
    <bean id="instanceaccountService" factory-bean="instanceFactory" factory-method="getBean"></bean>

InstanceBeanFactory:

package factory;

import rumen.AccountServiceImpl;
import rumen.IAccountService;

public class InstanceBeanFactory {
	
	public IAccountService getBean() {
		return new AccountServiceImpl();
	}
}

Client:

package rumen;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

//表现层
public class Client {

	//获取Spring的核心容器,并根据id获取对象
	public static void main(String[] args) throws ClassNotFoundException {
		//1.获取Spring的核心容器
		ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
		//2.根据id获取对象
		
		IAccountService as = (IAccountService) ac.getBean("instanceaccountService");
		
		System.out.println(as);

	}

}

2、bean对象的作用范围

它通过配置的方式来指定

配置的属性:bean的scope标签

属性:singleton:单例的。默认(常用)

           prototype:多例的

           request:请求范围

           session:会话范围

           global-session:全局会话范围

 

3、bean对象的生命周期

单例对象:

出生:容器创建时,对象出生

活着:只要容器存在,对象就一直存在

死亡:容器销毁,对象死亡

多例对象:

出生:每次使用时,容器会创建对象

活着:只要对象一直使用,就一直活着

死亡:当对象长时间不用,并且也没呀其他对象引用时,java的垃圾回收器回收

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值