动态代理:
代理设计模式: 让代理角色帮助真实完成一件事情 (对业务功能进行增强!)
静态代理:
特点:代理角色和真实角色必须实现同一个接口
静态代理
控制反转(依赖注入)
IOC方式对象的生命周期由Spring框架提供的IoC容器来管理,直接从IoC容器中获取对象,控制权从应用程序交给IoC容器
借助"第三方"实现具有依赖管理对象之间的解耦
Dependency Inject(依赖注入) :由IoC容器在运行期间动态地将某种依赖关系注入到对象之中
益处:可维护性比较好
可复用性好
使用方式:
1.setter方法注入
2.构造方法注入
3.p标签注入
4.注解注入
Spring
两种核心容器:BeanFactory(org.springframework.beans.factory) 和 ApplicationContext(org.springframework.context)
将指定类配置给spring,让spring创建其对象的实例
<bean id="xxx" class="实体类包路径x.x.x.x"/>
指定容器注入属性;<property name="xxx" ref="指定另外bean的id"/>
//读取spring配置文件,并创建Spring容器
ClassPathXmlApplicationContext applicationContext =
new ClassPathXmlApplicationContext("spring-config.xml");
//获取bean对象
shopService = (ShopService) applicationContext.getBean("shopService");
XML装配方式
设值注入(Setter Injection)
构造注入(Constructor Injection)
前提条件:Bean类必须提供一个默认无参构造方法
Bean类必须为需要注入的属性提供对应的setter()方法
<bean id="user" class="com.qf.pojo.User">-->
<!--id注入进去了-->
<!--<property name="id" value="9527"></property>
<property name="name" value="张三丰"></property>
<property name="gender" value="男"></property>
<property name="age" value="25"></property>-->
<!--构造器注入-->
<!-- <constructor-arg name="id" value="2"></constructor-arg>
<constructor-arg name="name" value="高圆圆"></constructor-arg>
<constructor-arg name="gender" value="女"></constructor-arg>
<constructor-arg name="age" value="44"></constructor-arg>-->
<!--</bean>-->
<!--方式3:p标签注入 前提条件set方法存在-->
<!--<bean id="user" class="com.qf.pojo.User" p:id="3" p:name="张佳宁" p:gender="女" p:age="33">
</bean>
对包路径下的所有Bean文件进行扫描
<context:component- scan base-package="bean所在的包路径"/>
模式
Spring容器创建对象时机(推荐单例模式):
1)当容器创建完毕的时候,当前这些类被创建,同时并进行初始(默认是单例模式)
2)当容器使用完毕,关闭的时候,当前类对象被销毁,通知jvm来回收没有更多引用的对象!
Sring容器创建对象的时候:可以指定多例模式
scope="prototype"
lazy-init="true" 是在多例模式使用 配置是否懒加载初始化
(懒加载:按需加载)
多线程环境下,不同的用户去调用业务接口,需要在配置方式指定多例模式