Spring是一个轻量级控制反转(IoC)和面向切面(AOP)的容器开源框架。
轻量:轻量与重量是一个相对的概念,从大小与开销两方面而言Spring都是轻量的。EJB比较大,且其启动时需要消耗大量的内存、CPU等资源,所以是重量级框架;而Spring则不是,所以是轻量级框架。
其实关于IoC和AOP是什么,我也不是很清楚,会在明天学习后慢慢了解。
今天就是通过Spring几种创建对象方式,来了解Spring的便捷性。
首先创建一个com.jd包,在其中加入vo包和test包,分别创建Person和Test类。
创建好的结果如下:
在Person中代码如下:
public class Person {
public Person() {
super();
System.out.println("Person实例化对象创建完成");
}
}
如果我们要在Test中实例化Person,需要引包,还有Person per =new Person();如果是大型的项目中,这样是很麻烦的。
下面我们通过Spring,来自动创建Person对象:
首先导入4个jar包:build path ——>add build path.
然后在src中创建xml文件:
步骤如下:src——>new——>other——>Spring Bean Configuration File
:
点击finash,就可以了。
创建好之后,就在app.xml中配置:
app.xml初始界面如下:
app.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.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">
<bean id="p" class="com.jd.vo.Person" lazy-init="true" scope="prototype"></bean>
<bean name="d,date" class="java.util.Date"></bean>
</beans>
很明显只多了一句:<bean id="p" class="com.jd.vo.Person" lazy-init="true" scope="prototype"></bean>
这就是对app.xml完成了配置:
注意:
①:id只能有一个,但是name可以是多个值,在类中使用时,多个值同时生效,无论那个一个都是可以的
②:lazy-init懒加载,默认是不懒加载,如果是true时,那么就执行懒加载,只有当这个类被使用时,才会创建对象
③:scope有 四种类型可以选择。分别如下:
1)SingleTon:这将bean定义范围限定为每个Spring IoC容器的单个实例(默认)。
2)Prototype:这将单个bean定义范围限定为具有任意数量的对象实例。
3)request:这将bean定义范围限定为HTTP请求。仅在Web感知Spring ApplicationContext的上下文中有效。
4)session:这将bean定义范围限定为HTTP会话。仅在Web感知Spring ApplicationContext的上下文中有效。
test中代码如下:
package com.jd.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("app.xml");
Object obj = context.getBean("p");
System.out.println(obj);
obj = context.getBean("p");
System.out.println(obj);
obj = context.getBean("d");
System.out.println(obj);
}
}
我们执行后如果发现,执行了Person中的方法,那么就说明了Person对象被创建;
结果如下:
执行了Person中的方法,说明Person对象确实被创建;
方法二:通过scan的方式进行创建对象:
首先导入新的jar包,如图:
然后配置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.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">
<context:component-scan base-package="com.jd.vo"></context:component-scan>
</beans>
需要在Person类前加上Service或者Contrler或者Component
程序执行结果如下: