Spring 笔记《一》

什么是Spring

     Spring是一个轻量级的控制反转(IOC)和面向切面(AOP)的容器开源框架

IOC与DI

      IOC(控制反转)将对象的创建权反转给了Spring

      DI  (依赖注入)前提是必须拥有IOC的环境,Spring管理这个类的时候将这个类依赖的属性注入(设置)进来

Spring的使用

     

            //创建一个Spring IOC容器,在没有懒加载的情况下,该过程执行完就已经创建了对象
		ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("application.xml");
		//从IOC容器中获取Bean对象
		Student student = (Student)applicationContext.getBean("student");

Bean标签

     在application.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"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
	<!-- id属性:用来获取IOC容器中的Bean对象,具有唯一性 -->
	<!-- class属性:指定Bean对象由哪个类创建,类的全名 -->
	<bean id="student" class="com.zzu.vo.Student" lazy-init="true" scope="prototype">
		<property name="name" value="Tom"></property>
	</bean>
	
</beans>

    懒加载

     默认情况下IOC容器会把Bean对象实例化,可通过两种方式实现懒加载(即在使用该对象时才会实例化Bean对象,可以节省系统资源) 

     第一种:在beans标签中添加default-lazy-init="true",这会使该Beans标签中的所有bean实现懒加载。

<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"
	default-lazy-init="true">

      第二种:在bean标签中添加lazy-init = "true",仅会将该bean实现懒加载。

<bean id="student" class="com.zzu.vo.Student" lazy-init="true">
		<property name="name" value="Tom"></property>
	</bean>

scope:

     scope="singleton",默认值,IOC容器中只存在一个Java对象,此时Java对象为单例,即每次从IOC容器中获取的对象都是同一个对象

<bean id="student" class="com.zzu.vo.Student" lazy-init="true" scope="singleton">
		<property name="name" value="Tom"></property>
</bean>
public class Test {
	public static void main(String[] args) {
		//创建一个Spring IOC容器
		ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("application.xml");
		//从IOC容器中获取Bean对象
        //获取一个对象
		Student student = (Student)applicationContext.getBean("student");
		System.out.println(student);
		//再次获取一个对象
		Student student1 = (Student)applicationContext.getBean("student");
		System.out.println(student1);
	}
}

      scope="prototype",每次从IOC容器中获取的对象都是一个新的Java对象

<bean id="student" class="com.zzu.vo.Student" lazy-init="true" scope="prototype">
		<property name="name" value="Tom"></property>
</bean>

     

scope="request":每次HTTP请求都会创建一个新的Bean,该作用域只适用于WebApplicationContext环境;

scope="session":每次有新的会话都会创建一个新的Bean,该作用域只适用于WebApplicationContext环境;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值