属性注入
构造方法注入
- 索引方式
<bean class="com.bug.Book" name="book">
<constructor-arg index="0" value="Java"/>
<constructor-arg index="1" value="199"/>
</bean>
- 指定name
<bean class="com.bug.Book" id="book2">
<constructor-arg name="name" value="C++"/>
<constructor-arg name="price" value="99"/>
</bean>
set方法注入
前提是需要有setter方法
<bean class="com.bug.Book" id="book3">
<property name="name" value="python"/>
<property name="price" value="88.9"/>
</bean>
p名称空间注入
<bean class="com.bug.Book" id="book4" p:name="html" p:price="299.9">
</bean>
c名称注入
<bean class="com.bug.Book" id="book5" c:name="js" c:price="19"/>
复杂属性注入
对象注入
在Book类中添加User属性,添加相应属性的get/set方法
<bean class="com.bug.Book" id="book6">
<property name="user" ref="user"/>
</bean>
<bean class="com.bug.User" id="user">
<property name="name" value="xiaoyu"/>
<property name="age" value="12"/>
<property name="password" value="123"/>
</bean>
运行如下代码:
public static void main(String[] args) {
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("application.xml");
Book book= (Book) ctx.getBean("book6");
System.out.println(book);
}
结果:
Book{name='null', price=0.0, user=User{name='xiaoyu', password='123', age=12}}
数组和集合注入
在Book类中添加
private User[] users;
private List<String> author;
<bean class="com.bug.Book" id="book7">
<property name="name" value="python"/>
<property name="price" value="88.9"/>
<!--数组方式-->
<property name="users">
<array>
<ref bean="user"/>
<bean class="com.bug.User" id="user2">
<property name="name" value="li"/>
<property name="password" value="123"/>
<property name="age" value="18"/>
</bean>
</array>
</property>
<!--集合方式-->
<property name="author">
<list>
<value>libai</value>
<value>wanger</value>
<value>zhangsan</value>
</list>
</property>
</bean>
<bean class="com.bug.User" id="user">
<property name="name" value="xiaoyu"/>
<property name="age" value="12"/>
<property name="password" value="123"/>
</bean>
Map注入
<property name="user">
<map>
<entry key="username" value="xiaoyu"/>
<entry key="password" value="123"/>
</map>
</property>
properties注入
添加属性private Properties properties以及对于的get/set方法
<property name="properties">
<props>
<prop key="学号">20190604</prop>
<prop key="性别">男</prop>
<prop key="姓名">小明</prop>
</props>
</property>