Spring(1)初识Spring+IOC(控制反转)+DI(依赖注入)(附:快速入门案例)

xiaoxiao2021-02-28  85

1 Spring概念+IOC+DI

①Spring是容器框架,用于配置各种bean,并维护bean之间的关系。 ②Spring中几个重要概念: bean:是Java中任何一种对象,Javabean、service、action、数据源、dao IOC(控制反转inverse of control):就是把创建对象(bean)和维护对象(bean)之间关系的权利,从程序中转移到spring的容器(applicationContext.xml)中,而程序本身不再维护 DI(dependency injection依赖注入):实际上DI和IOC是同一个概念,spring设计者认为DI更准确的表示spring的核心技术(依赖【对象之间关系】和注入【属性注入、赋值】)

2 快速入门案例

原理图: ①引入Spring开发包(最小配置spring-framework-2.5.5\dist\spring.jar,以及spring-framework-2.5.5\lib\jakarta-commons\commons-logging.jar) UserService 类:

public class UserService { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } public void sayHello() { System.out.println("hello " + name); } }

②创建spring的核心文件applicationContext.xml(放在src目录下) 编写规范可以从spring-framework-2.5.5\samples中参考 配置bean:

<?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: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"> <!-- 在容器文件中配置bean 当spring框架加载的时候,spring就会自动创建一个bean对象,并放入内存 相当于: UserService userService = new UserService(); userService.setName("jiaozl"); --> <bean id="userService" class="com.service.UserService"> <!-- 这里就体现出注入的概念 --> <property name="name"> <value>jiaozl</value> </property> </bean> </beans>

③使用bean

// 得到Spring的applicationContext容器对象 ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml"); // 通过java反射机制得到对象 UserService us = (UserService) ac.getBean("userService"); us.sayHello();

3 维护两个bean之间的关系

Service类

public class IDCardService { private String IDS; } public class UserService { private String name; private IDCardService userId; public void sayHello() { System.out.println("hello " + name + " my id is " + userId.getIDS()); } }

applicationContext.xml

<bean id="userService" class="com.service.UserService"> <!-- 这里就体现出注入的概念 --> <property name="name"> <value>jiaozl</value> </property> <!-- 在userService中引用idCardService bean --> <property name="userId" ref="idCardService"></property> </bean> <bean id="idCardService" class="com.service.IDCardService"> <property name="IDS" value="99885566"></property> </bean>

使用

// 得到Spring的applicationContext容器对象 ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml"); UserService us = (UserService) ac.getBean("userService"); us.sayHello();
转载请注明原文地址: https://www.6miu.com/read-57081.html

最新回复(0)