您的位置:首页 > 编程语言 > Java开发

【Spring】【对<bean>注入各种信息】【简单属性,对象属性,集合属性,构造器】

2017-12-30 10:32 761 查看

注入简单属性

<property name="xx" value="XX">


对应字段需要setter方法

会自动转换属性(String Long Integer BigDcimal)

public class User {

private String name;
private Long age;
}


<bean id="user" class="dao.impl.User">
<property name="name" value="armo"/>
<property name="age" value="100"/>
</bean>


注入对象属性

<property name="XXXX" ref="bean对象的id"/>


将bean对象,当成属性注入到另外一个bean对象

对象属性不需要setter方法

<bean id="sessionFactory" class="XXX.XXX.HibernateTransactionManager" />

<bean id="employeeDAO" class="dao.impl.EmployeeDAOImpl" >
<property name="sessionFactory" ref="sessionFactory"/>
</bean>


注入集合属性

list和set

list和set操作一样

需要setter

<list>
的value-type属性可以设置所有元素的类型

<value>
的type属性可以设置单个成员的类型

没有声明类型情况,默认使用String

public class User {
public List list;
}


<bean id="user" class="dao.impl.User">
<property name="list">
<list>
<value type="java.lang.String">aaa</value>
<value type="java.lang.Long">22</value>
<value type="java.lang.Integer">22</value>
<ref bean="sessionFactory"/>
</list>
</property>

</bean>


实例 配置sessionFactory工厂时候,声明映射文件的方式就是list

<bean id="sessionFactory" class="LocalSessionFactoryBean">
<!-- Hibernate的映射文件地址 -->
<property name="mappingDirectoryLocations">
<list>
<value>classpath:XXX.domain</value>
</list>
</property>
</bean>


properies

方式一(常用,不能写中文) 举例 Spring集成Hibernate:Hibernate的属性配置

<bean id="sessionFactory" class="LocalSessionFactoryBean">
<!-- Hibernate的配置信息 -->
<property name="hibernateProperties">
<value>
hibernate.hbm2ddl.auto=update
hibernate.show_sql=true
hibernate.dialect=org.hibernate.dialect.MySQLDialect
hibernate.cache.use_second_level_cache=true
</value>
</property>
</bean>


方式二(能写中文)

<bean id="user" class="dao.impl.User">
<property name="properties">
<props>
<prop key="XXX">中文</prop>
<prop key="XXX">XXX</prop>
<prop key="XXX">XXX</prop>
</props>
</property>
</bean>


map(不常用)

<bean id="user" class="dao.impl.User">
<property name="map">
<map key-type="键类型" value-type="值类型">
<entry key="" value="" value-type="值类型" value-ref="beanID" key-ref="beanID" />
</map>
</property>
</bean>


注入构造器属性

在默认情况下.Spring是通过bean类的无参构造器反射创建对象.

注入构造器,让Spring容器通过有参构造器来创建对象

public class User {
private String name;
private Integer age;
private Department dept;
public User(String name, Integer age, Department dept) {
super();
this.name = name
ad9f
;
this.age = age;
this.dept = dept;
}


<!--默认按照构造器的形参位置(索引)来注入值-->
<bean id="user" class="dao.impl.User">
<constructor-arg value="armo"/> //对应索引为1形参
<constructor-arg value="12"/>    //对应索引为2形参
<constructor-arg ref="beanID"/>   //对应索引为3形参
</bean>


Spring提供三种方式来定位

name=”形参名字”
<constructor-arg value="12" name="age"/>
//对应age

index=”形参的索引,从0开始”
<constructor-arg value="armo" index="1"/>  //对应索引为1的形参(name)


type=”形参类型”
<constructor-arg value="12" type="java.lang.Integer"/> //对应形参类型为Integer的形参(age)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  spring bean
相关文章推荐