spring官网代码示例
1、不同类型的注入方式
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="address" class="com.hu.pojo.Address">
<property name="address" value="lalala"/>
</bean>
<bean id="student" class="com.hu.pojo.Student">
<!--注入value-->
<property name="name" value="pengpeng"/>
<!--第二种bean注入,ref-->
<property name="address" ref="address"/>
<!--String[]数组注入-->
<property name="book">
<array>
<value>红楼梦</value>
<value>水浒传</value>
</array>
</property>
<!--list注入-->
<property name="hobbys">
<list>
<value>听歌</value>
<value>make</value>
</list>
</property>
<!--map注入-->
<property name="card">
<map>
<entry key="gender" value="male"/>
</map>
</property>
<!--set注入-->
<property name="games">
<set>
<value>lol</value>
</set>
</property>
<!--空值-->
<property name="wife" value=""/>
<!--properties注入-->
<property name="info">
<props>
<prop key="学号">15200000</prop>
<prop key="专业">CS</prop>
</props>
</property>
</bean>
</beans>
2、p-namespace以及c-namespace
2.1 添加方法
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
<!--加上这个-->
xmlns:c="http://www.springframework.org/schema/c"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="user" class="com.hu.pojo.User" p:name="鹏鹏"/>
</beans>
2.2 p和c区别
p-namespace:通过值进行注入,简洁方便
c-namespace:通过构造器进行注入,需要在java类文件中加上有参构造器和无参构造器