Spring注入方式
1.属性注入(setter方法注入,property)
2.构造注入(constructor-arg)
3.静态工厂注入
4.实例工厂注入
注意:注入只会注入到Spring用getbean或得到的对象,自己创建的对象(new XXX())不会被Spring注入
属性注入
<bean id="b" class="kkk.kkk.kkb">
</bean>
<bean id="c" class="kkk.kkk.kkc">
</bean>
<bean id="a" class="com.xxx.xxx">
<property name="" ref="b"></property>
<property name="" ref="c"></property>
</bean>
构造注入
<bean id="b" class="kkk.kkk.kkb">
</bean>
<bean id="a" class="com.xxx.xxx">
<constructor-arg name="" ref="b"></property>
</bean>
集合注入
<property name="xxx">
<list>
<value>...</value>
<value>...</value>
</list>
</property>
<property name="xxx">
<props>
<prop key="...">...</prop>
<prop key="...">...</prop>
</props>
</property>
p标签(使用setter方法注入)
普通成员p标签方式注入
<bean id="" class="" p:price="">
对象成员注入
<bean id="p" class="xx.xxx.xx">
<bean id="" class="" p:parent-ref="p">
list成员注入
<util:list id="bbbb">
<value>x</value>
<value>xx</value>
<value>xxx</value>
</util:list>
<bean id="ccc" class="xxx.xxx.xxx" p:xxxxxx-ref="bbbb"
自动注入
no:顾名思义, 显式指明不使用Spring的自动装配功能
byName:根据属性和组件的名称匹配关系来实现bean的自动装配
byType:根据属性和组件的类型匹配关系来实现bean的自动装配,有多个适合类型的对象时装配失败
constructor:要求待装配的bean有相应的构造函数,先根据类型再根据名字
detect:利用Spring的自省机制判断使用byType或是constructor装配(少用)
通过byName自动注入(需要bean的id与被注入的对象名字相同才可以)
class C{
public PP p; //这个名字和beanId名字必须匹配
public void setP(PP p){
this.p = p;
}
}
<bean id="p" class="..."></bean>
<bean id="c" class="xx.xx" autowire="byName"></bean>
通过byType自动注入(不可以有多个类型一样的)
<bean id="c" class="xx.xx" autowire="byType"></bean>
通过constructor自动注入(必须有一个无参构造器否则要用Constructor对象得到bean对象)
<bean id="c" class="xx.xx" autowire="constructor"></bean>
作用域 scope
1.singleton:只生成一个实例
- 容器加载时生成,容器关闭时销毁。
- 生成实例会调用init方法 (init-method=“xxx”),销毁时调用destroy方法 (destroy-method=“xxx”)
2.prototype:每次调用就生成一个实例
- 每次请求时生成
- java虚拟机中自己销毁
以下在web中使用:
3.Request:每次请求生成一个实例
4.Session:每次会话生成一个实例
5.global-session:在portlet中使用(单点登录)
<bean ... scope="singleton" init-method="init" destroy-method="destroy"></bean>
参考
https://blog.youkuaiyun.com/sinat_34596644/article/details/53080026?utm_source=copy