各种类型属性的注入语法
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 http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="address" class="com.blackcat.pojo.Address">
<property name="address" value="杭州"/>
</bean>
<bean id="student" class="com.blackcat.pojo.Student">
<!--第一种:普通值注入,value-->
<property name="name" value="黑猫"/>
<!--第二种:Bean注入,ref-->
<property name="address" ref="address"/>
<!--数组-->
<property name="books">
<array>
<value>红楼梦</value>
<value>三国演义</value>
<value>西游记</value>
<value>水浒传</value>
</array>
</property>
<!--集合-->
<property name="hobbys">
<list>
<value>听歌</value>
<value>敲代码</value>
<value>看电影</value>
</list>
</property>
<!--map-->
<property name="cart">
<map>
<entry key="身份证" value="23453523453"/>
<entry key="银行卡" value="232t59832579"/>
</map>
</property>
<!--set-->
<property name="games">
<set>
<value>LoL</value>
<value>honour of king</value>
<value>BOBO</value>
</set>
</property>
<!--null-->
<!--<property name="wife" value=""/>-->
<property name="wife">
<null/>
</property>
<property name="info">
<props>
<prop key="学号">145235252626</prop>
<prop key="姓名">小佳</prop>
<prop key="性别">女</prop>
<prop key="年龄">21</prop>
<prop key="driver">华为</prop>
<prop key="url">huawei</prop>
<prop key="username">root</prop>
<prop key="password">123456</prop>
</props>
</property>
</bean>
</beans>
2、测试:
import com.blackcat.pojo.Student;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
Student student = (Student) context.getBean("student");
// System.out.println("student.getAddress() = " + student.getAddress());
System.out.println("student.toString() = " + student.toString());
}
}
3、结果:
student.toString() = Student{name='黑猫', address=Address{address='杭州'}, books=[红楼梦, 三国演义, 西游记, 水浒传], hobbys=[听歌, 敲代码, 看电影], cart={身份证=23453523453, 银行卡=232t59832579}, games=[LoL, honour of king, BOBO], wife='null', info={学号=145235252626, 性别=女, password=123456, url=huawei, driver=华为, 姓名=小佳, username=root, 年龄=21}}
Process finished with exit code 0