Spring---helloworld实例
1、什么是Spring框架?
spring是J2EE应用程序框架,是轻量级的IoC和AOP的容器框架,主要是针对JavaBean的生命周期进行管理的轻量级容器,可以单独使用,也可以和Struts框架,Hibernate框架等组合使用。
2、为什么使用Spring框架?
在使用Spring框架之前,Service层想要调用Dao层的方法,必须在Service层中新建一个Dao层的对象,增加了层与层之间的耦合性。而Spring就解决了这个问题,我们只需要在appliationContext.xml中配置多个bean就可,每个bean对应一个Java类,想要访问Dao层的对象时,就先获取其对应的bean,便可以访问其中的方法。至于对象是这么创建的,就交给Spring框架去做就好了。减少了层与层之间的耦合性。
具体的实例如下:
1、新建一个Java工程,添加Spring 3.1支持,会发现,在src下多一个名为applicationContext.xml的配置文件,这是spring的配置文件:
<?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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">
</beans>
2、配置applicationContext.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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">
<bean name="helloService" class="com.etc.service.HelloService"></bean>
</beans>
3、在src下新建com.etc.dao包,在包下新建一个类HelloService.java:
package com.etc.service;
public class HelloService {
public void sayHello(){
System.out.println("hello");
}
}
4、在工程下新建test源文件夹,在文件夹下新建com.etc.test包,在包下新建HelloServiceTest.java类:
package com.etc.test;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.etc.service.HelloService;
public class HelloServiceTest {
@Test
public void test1(){
/*想要调用HelloService中的hello()方法
原始的方法
1、New一个这个类的对象
HelloService helloService = new HelloService();
2、调用这个类的方法
helloService.sayHello();*/
//现在,使用Sping框架之后的方法
//1、加载spring配置
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
//2、通过配置文件获取所需要的类,不需要新建类的对象
HelloService helloService = (HelloService) context.getBean("helloService");
//3、调用这个类的方法
helloService.sayHello();
}
}
提示:
Spring的一些常用的配置属性如下:
1、lazy-init:懒加载
false:默认值,加载完spring的配置文件之后,就将配置文件中的所有的bean都先加载完。
true:加载完spring的配置文件之后,并不会加载完所有的bean,而是等到要用的时候再加载。
2、scope:范围
protype:原型,每次都新建一个对象,Spring中有多个副本
singleton:单例,默认值,每次用的都是同一个对象,Spring中只有一个bean