Spring是为了简化EJB(声明式的编程模型)开发而出现的解决方案,
首先要明确的给出Spring一个定义:Spring是一个轻量级的IoC和AOP容器框架。这个定义主要表现在:
Spring 框架是一个分层架构,由 7 个定义良好的模块组成。Spring 模块构建在核心容器之上,核心容器定义了创建、配置和管理 bean 的方式
组成 Spring 框架的每个模块(或组件)都可以单独存在,或者与其他一个或多个模块联合实现。每个模块的功能如下:
BeanFactory
,它是工厂模式的实现。BeanFactory
使用控制反转 (IOC) 模式将应用程序的配置和依赖性规范与实际的应用程序代码分开。
下面来用Spring实现一个那个最常见最无奈的程序Hello World!
1:先写一个问候的接口(实现与接口分离是好的习惯)
package com.spring.study.hello; public interface GreetingService { public void sayGreeting(); }
2:实现类的编写
package com.spring.study.hello; public class GreetingServiceImpl implements GreetingService { // 声明 问候的字符串 private String greeting; public GreetingServiceImpl() { } public GreetingServiceImpl(String greeting) { this.greeting = greeting; } // 打印方法 public void sayGreeting() { System.out.println(greeting); } public String getGreeting() { return greeting; } public void setGreeting(String greeting) { this.greeting = greeting; } }
3: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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd"> <bean id="greetingService" class="com.spring.study.hello.GreetingServiceImpl"> <property name="greeting"> <value>Hello world!</value> </property> </bean> </beans>
在XML文件在Spring容器中声明了一个GreetingServiceImpl的实例,并且将Hello world!的值赋给greeting属性。
4:编写主类
package com.spring.study.hello; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class HelloApp { public static void main(String[] args) throws Exception { // 载入配置文件 ApplicationContext factory = new ClassPathXmlApplicationContext( "applicationContext.xml"); // 得到GreetingService的引用 GreetingService greetingService = (GreetingService) factory .getBean("greetingService"); // 调用打印方法 greetingService.sayGreeting(); } }
这样一个简单的不能在简单的Spring例子就完成了。它将一个字符串注入到了bean中。
不过Spring真正的威力是如何使用IOC将一个Bean注入到另一个Bean中。