Spring学习日志(一)
Spring作为一个开源框架,它的最大特点就是实现业务分层。它的核心是:IOC和AOP,也就是控制反转和面向切面的编程。当然这个框架也集成了其他的功能,例如测试,可以有效地集成其他框架等等。
Spring的使用有两种方法,一种是标签定义法,一种就是通过xml实现。在这里就讲XML语言实现。这就涉及到Spring的xml格式,里面主要包含两大类,命名空间(放在“beans”标签中,一般自动生成)和自定义“bean”(在这个标签中定义“id”(标记)和“class”(包+实现类)。
逻辑过程如下
具体例子如下:
抽象类
demoInterface.class 文件
package com.action.interfaces;
public interface demoInterface {
public void hello();
}
实现类
demoImplement.class 文件
package com.action.implement;
import com.action.interfaces.demoInterface;
public class demoImplement implements demoInterface{
@Override
public void hello() {
System.out.println("hello World!");
}
}
Spring xml配置
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-4.1.xsd">
<bean id="testSpring" class="com.action.implement.demoImplement"></bean>
</beans>
测试
@Test
public void testDemoInterface(){
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
demoInterface demo = (demoInterface) context.getBean("testSpring");
demo.hello();
}
结果
提示
Spring开发除了Spring框架所需的Jar包以外,还需要一个commons-logging.jar包,如果缺乏这个jar包,程序就不能找到对应的类。
commons-logging.jar下载页面