spring温习笔记-入门-依赖注入

来源:互联网 发布:淘宝宠物用品一件代发 编辑:程序博客网 时间:2024/04/19 17:46

Spring容器最大的作用便是解耦合,所有的控制反转、依赖注入其实是一个意思,创建被调用者的实例由Sping容器来完成,然后注入调用者。


spring架包可以去官方下载,也可以移驾这里:点击下载spring3.0.5的架包


创建helloworld实例


1、创建一个工程,引用spring架包、common-logging.jar

2、创建一个bean.xml文件

<?xml version="1.0" encoding="UTF-8"?><beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns="http://www.springframework.org/schema/beans"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.0.xsd"><!-- 将TestService类部署成Spring容器中的Bean  --><bean id="testService" class="xl.TestService"><property name="name" value="world"/></bean></beans>

3、创建一个service文件  其实就类似一个JavaBean

package xl;public class TestService {private String name;public void setName(String name) {this.name = name;}public void call() {System.out.println("hello,"+name);}}

4、运行  Hello,World

package xl;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class SpringTest {/** * @param args */public static void main(String[] args) {ApplicationContext appContext=new ClassPathXmlApplicationContext("bean.xml");TestService test=appContext.getBean("testService",TestService.class);test.call();}}

5、输出结果

Hello,World


项目打包下载:点击下载