1.普通创建bean(默认为无参构造创建)
<bean id="user" class="com.kuang.pojo.User">
<property name="name" value="kuangshen"/>
</bean>
2.通过有参构造创建bean(三种方式)
<!-- 第一种根据index参数下标设置 -->
<bean id="userT" class="com.kuang.pojo.UserT">
<!-- index指构造方法 , 下标从0开始 -->
<constructor-arg index="0" value="kuangshen2"/>
</bean>
<!-- 第二种根据参数名字设置 -->
<bean id="userT" class="com.kuang.pojo.UserT">
<!-- name指参数名 -->
<constructor-arg name="name" value="kuangshen2"/>
</bean>
<!-- 第三种根据参数类型设置 -->
<bean id="userT" class="com.kuang.pojo.UserT">
<constructor-arg type="java.lang.String" value="kuangshen2"/>
</bean>
3.xml的bean标签配置
<bean id="hello" name="hello2 h2,h3;h4" class="com.kuang.pojo.Hello">
4.各种类型数据的bean注入(9种方式)
1.常量
<bean id="student" class="com.kuang.pojo.Student">
<property name="name" value="小明"/>
</bean>
2.ref引用类型
<bean id="student" class="com.kuang.pojo.Student">
<property name="name" value="小明"/>
<property name="address" ref="addr"/>
</bean>
3.数组注入(books为一个数组)
<bean id="student" class="com.kuang.pojo.Student">
<property name="books">
<array>
<value>西游记</value>
<value>红楼梦</value>
<value>水浒传</value>
</array>
</property>
</bean>
4.list注入
<property name="hobbys">
<list>
<value>听歌</value>
<value>看电影</value>
<value>爬山</value>
</list>
</property>
5.map注入
<property name="card">
<map>
<entry key="中国邮政" value="456456456465456"/>
<entry key="建设" value="1456682255511"/>
</map>
</property>
6.set注入
<property name="games">
<set>
<value>LOL</value>
<value>BOB</value>
<value>COC</value>
</set>
</property>
7.null注入
<property name="wife"><null/></property>
8.properties注入
<property name="info">
<props>
<prop key="学号">20190604</prop>
<prop key="性别">男</prop>
<prop key="姓名">小明</prop>
</props>
</property>
9.p命名空间和c命名空间注入
导入约束
xmlns:p=“http://www.springframework.org/schema/p”
xmlns:c=“http://www.springframework.org/schema/c”
c命名空间是有参构造命名,而p空间是直接对应属性命名set方法。
5.自动装配
1.自动注入引用类型(还有两个引用类型cat/dog。都是user的子类。)
public class User {
private Cat cat;
private Dog dog;
private String str;
}
<bean id="user" class="com.kuang.pojo.User" autowire="byName">
<property name="str" value="qinjiang"/>
</bean>
<bean id="dog" class="com.kuang.pojo.Dog"/>
<bean id="cat" class="com.kuang.pojo.Cat"/>
<bean id="cat2" class="com.kuang.pojo.Cat"/>
<bean id="user" class="com.kuang.pojo.User" autowire="byType">
<property name="str" value="qinjiang"/>
</bean>
注意byType必须只能是一个类型,有两个同类型的cat会报错。
6.注解开发
引入头
xmlns:context=“http://www.springframework.org/schema/context”
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
开启注解支持
context:annotation-config/
然后就可以使用@AutoWired
如果@AutoWired加上@qualifier,两个合并使用。@qualifier可以指定对应装配的name。使用byname类型进行装配。
@Resource等于上面两者的合并功能。