标签:
Spring的主要功能是控制反转和面向切面编程,下面我们就来编写第一个spring的程序来体验一下控制反转
首先是加载配置文件
<?xml version="1.0" encoding="UTF-8"?>
<!--
- Middle tier application context definition for the image database.
-->
<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"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
</beans>
下面我们在程序中加载配置文件
ApplicationContext ac = new ClassPathXmlApplicationContext("spring.xml");
然后新建类
package com.service.impl;
import com.service.Service;
public class ServiceBean implements Service {
@Override
public void save(){
System.out.println("save()");
}
}
抽取出类的接口 refactor----->extract interface
然后在测试方法中孔子反转
package junit.test;
import static org.junit.Assert.*;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.service.Service;
public class SpringTest {
@Test
public void test() {
ApplicationContext ac = new ClassPathXmlApplicationContext("spring.xml");
Service service = (Service)ac.getBean("service");
service.save();
}
}
标签:
原文地址:http://www.cnblogs.com/dbqjava/p/4446532.html