Spring set 注入不同类型的参数

案例

  • 建立复杂的数据类型
    Student类
public class Student {

    private String name;
    private Address address;
    private List<String> books;
    private Map<String,String> card;
    private Properties info;
    private String winner;
    private boolean isMale;
// 注意加上相应的set方法,和toString
}

address类

public class Address {
    private String province;
// 注意加上相应的set方法,和toString
}
  • 建立beans.xml的spring配置文件
<?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">
<!--几种不同的数据类型set注入的方式-->
    <bean id="address" class="com.mao.pojo.Address">
        <property name="province">
            <value>北京</value>
        </property>
    </bean>
    <bean id="student" class="com.mao.pojo.Student" name="stu">
        <property name="name" value="猫猫"/>
        <property name="address" ref="address"/>
        <property name="books">
            <array value-type="java.lang.String">
                <value>java一点通</value>
                <value>c语言程序设计</value>
                <value>python程序设计</value>
                <value>网络安全和攻防</value>
            </array>
        </property>
        <property name="card">
            <map>
                <entry key="card_id" value="123123123"/>
                <entry key="name" value="ccard"/>
            </map>
        </property>
        <property name="info">
            <props>
                <prop key="name">Mao</prop>
                <prop key="sex">male</prop>
                <prop key="goals">89</prop>
            </props>
        </property>
        <property name="male" value="false"/>
        <property name="winner">
            <null/>
        </property>
    </bean>

</beans>
  • 测试
@Test
public void test(){
	ApplicationContext context = new ClassPathXmlApplicationContext("studentbean.xml");
        Student student = (Student) context.getBean("student");
        System.out.println(student);
        /*
        Student{
            name='猫猫',
            address=Address{
                province='北京'
                },
            books=[java一点通, c语言程序设计, python程序设计, 网络安全和攻防],
            card={card_id=123123123, name=ccard},
            info={sex=male, name=Mao, goals=89},
            winner='null', isMale=false
            }

         */
}

详细见官方文档
https://docs.spring.io/spring-framework/reference/core/beans/dependencies/factory-collaborators.html#beans-some-examples

posted @ 2023-08-19 15:58  MaoShine  阅读(16)  评论(0编辑  收藏  举报