SpringIOC-控制反转
概念
IOC Inversion of Control : 控制反转,是一个理论,一个指导思想。指导开发人员如何使用对象,管理对象的。把对象的创建,属性赋值,对象的生明周期都交给代码之外的容器管理。
IOC 控制反转
就是将对象的控制权转移出去,将对象的创建、初始化、销毁交给容器管理,容器管理对象的生命周期,将通过new创建对象的过程交给spring容器完成。
DI依赖注入
对象之间的依赖关系,通过spring容器实现对象与对象之间的关系,目的是为了解耦
1、bean实例化
1.1 无参造器
<bean id="定义bean名称" class="路径+类名"></bean>
1.2 静态工厂
<bean id="定义bean名称" class="路径+类名" factory-method="静态方法"></bean>
1.3 普通工厂
<bean id="定义工厂名称" class="路径+工厂类名"></bean> <bean id="定义名称" factory-bean="工厂名称" factory-method="工厂方法"></bean>
2、属性的注入
2.1 构造器注入
<bean id="定义bean名称" class="路径+类名"> <constructor-arg index="" value="注入基本数据类型"></constructor-arg> <constructor-arg index="" ref="注入对象"></constructor-arg> </bean>
2.2 set注入
<bean id="定义bean名称" class="路径+类名"> <property name="" value=""></property> <property name="" ref="”></property> </bean>
2.2 命名空间注入
<bean id="定义bean名称" class="路径+类名" p:属性名称="属性值"></bean>
2.3 list set map注入
<bean id="定义bean名称" class="路径+类名"> <property name="list集合属性名称"> <list> <value>值</value> <value>值</value> </list> </property> <property name="set集合属性名称"> <set> <value>值</value> <value>值</value> </set> </property> <property name="map集合属性名称"> <map> <entry key="键" value="值"></entry> <entry key="" value=""></entry> </map> </property> </bean>
3、spring注解
<?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:mvc="http://www.springframework.org/schema/mvc" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:task="http://www.springframework.org/schema/task" xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd"> </beans> <context:component-scan base-package="扫描的基本包"></context:component-scan>
-
@Component 通用注册组件(bean)(类上的注解)
value属性:指定baen的id 如何不指定值,它的值就是首字母小写的类名
-
@Service:业务层注解
-
@Repository 持久层注解
-
@Autowired :注入对象类型,帮我们自动实例化对象。(属性和方法上注解)