spring框架学习

Spring是一个类的容器实例化托管框架,可以实现对实现类的实例化进行动态的托管。更可以实现控制反转。控制

反转就是应用本身不负责倚赖对象的创建和维护,倚赖对象的创建和维护是通过其他的外部容器负责的,这样的控制

权就由应用转移到了容器。控制权的转移就是所谓的反转。


下面我们来说一下一个简单的Spring框架的搭建和实例.首先下载下来spring的压缩包,在解压后的dist文件夹下

面有spring.jar和commons-logging.jar这两个JAR包,这就是实现最简单的spring框架所必须的包,然后就是

在docs/reference下面的参考手册,里面有spring的配置文件写法。导入包完成后,最好在src目录下面建立beans.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

<bean id="personService" class="com.bird.service.impl.PersonServerImpl"></bean>
</beans>



然后写一个类和抽取出接口

package com.bird.service;

public interface PersonServer {

void save();

}

package com.bird.service.impl;

import com.bird.service.PersonServer;

public class PersonServerImpl implements PersonServer {

@Override
public void save(){
System.out.println("save()方法调用");
}
}


然后在beans.xml中配置这个类就可以使用spring实例化这个类了,下面的操作全部都是面向接口的编程了。

package junit.test;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.bird.service.PersonServer;

public class SpringTest {

@Test
public void test(){
ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
PersonServer s = (PersonServer)ctx.getBean("personService");
s.save();
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值