Spring 小细节

[size=large][color=red]1. 在配置文件中id 和 name区别[/color][/size]

<bean name="u" class="com.bczq.dao.impl.UserDAOImpl">
</bean>

<bean id="u" class="com.bczq.dao.impl.UserDAOImpl">
</bean>

上面两种基本一样,只是name可以包含特殊字符.一般情况下用name

[size=large][color=red]2. pojo初始化时候设指定值[/color][/size]
如有下面的一个类

public class UserDAOImpl{
private int daoId;
private String daoStatus;
public int getDaoId() {
return daoId;
}
public void setDaoId(int daoId) {
this.daoId = daoId;
}
public String getDaoStatus() {
return daoStatus;
}
public void setDaoStatus(String daoStatus) {
this.daoStatus = daoStatus;
}
}

则可以同过配置文件在初始化时候进行赋值

<bean name="userDAOImpl" class="com.bczq.dao.impl.UserDAOImpl">
<property name="daoId" value="8"></property>
<property name="daoStatus">
<value>good</value>
</property>
</bean>


[size=large][color=red]3. bean 的scopes[/color][/size]

<bean id="userService" class="com.bczq.service.UserService" scope="prototype">
</bean>

常用的值有如下:
1 singleton 单例
2.proptotype 每次创建新的对象


[size=large][color=red]3.bean的 autowire 属性[/color][/size]

<bean id="userService" class="com.bjsxt.service.UserService" scope="prototype" autowire="byType">
</bean>


1 no
不使用Autowire,引用关系显示声明,spring的reference也建议不用autoware,因为这会破坏模块关系的可读性,原文如下:
Note: as has already been mentioned, for larger applications, it is discouraged to use autowiring because it
removes the transparency and the structure from your collaborating classes.

2 byName
用名称关联,如果指定了这种模式,如
<bean id="userManagerTarget" class="com.mdcchina.jianghu.logic.UserManager" >
<property name="baseDAO"/>
</bean>
这样对于bean userManagerTarget的属性baseDAO,spring就会自动去引用同名的bean,也就是上面的声明和下面是等价的:
<bean id="userManagerTarget" class="com.mdcchina.jianghu.logic.UserManager" >
<property name="baseDAO">
<ref local="baseDAO"/>
</property>
</bean>

3 byType
和前面的byName类似的,就是这个属性会在整个beanFactory定义里找和这个属性一样的bean自动关联上,如果有2个或更多这个类型的bean在beanFactory的定义里,就直接抛异常了,如果没有,就什么都不发生,这个属性就是null,所以这个只适用与这个属性的类型有且只有一个同类的bean在spring里定义

4 constructor
这个的意思我没有确定的把握,不过感觉用途也不会大,好像是用构造函数新建一个属性类型的bean并关联上,reference原文是:
This is analogous to byType, but applies to constructor arguments. If there isn't exactly one
bean of the constructor argument type in the bean factory, a fatal error is raised.

5 autodetect
这个的意思好像是说自动决定用byType还是constructor方式,原文如下:
Chooses constructor or byType through introspection of the bean class. If a default
constructor is found, byType gets applied.

综上所述,感觉上只有byName比较实用一些,但是spring的reference还是不推荐在定义中用这个功能


[size=large][color=red]4.bean的 lazy-init="true"属性[/color][/size]

< beans default-lazy-init ="true" >
< bean lazy-init ="true" >


默认情况下会在容器启动时初始化bean, 但是我们可以指定Bean节点的 lazy-init="true" 来延迟初始化bean,这时候,只有第一次获取bean才会初始化bean。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值