01 spring中bean的配置与使用

本专辑将介绍spring ioc的相关特性。我们先来看一下spring中bean的配置与使用。

1、前提约束

2、操作步骤

  • 在src文件夹创建net.wanho.entity.Phone.java,内容如下:
package net.wanho.entity;
public class Phone implements Serializable {
    private String areaCode;
    private String phoneNumber;
    //无参构造方法、有参构造方法、get/set方法以及toString方法
}
  • 在src文件夹创建net.wanho.entity.User.java,内容如下:
package net.wanho.entity;
public class User implements Serializable {
    private int id;
    private String name;
    private Phone phone;
    public User(int id, String name) {
        this.id = id;
        this.name = name;
    }
    //无参构造方法、有参构造方法、get/set方法以及toString方法
}
  • 在src文件夹创建一个bean.xml,内容如下:
<bean id="user0" class="net.wanho.entity.User">
        <constructor-arg value="1"></constructor-arg>
        <constructor-arg value="ali"></constructor-arg>
    </bean>
<bean id="user" class="net.wanho.entity.User">
        <property name="id" value="123"></property>
        <property name="name" value="ali"></property>
        <property name="phone" ref="phone"></property>
</bean>
<bean id="phone" class="net.wanho.entity.Phone">
        <property name="areaCode" value="025"></property>
        <property name="phoneNumber" value="86187215"></property>
</bean>
<bean id="user1" class="net.wanho.entity.User">
        <property name="id" value="123"></property>
        <property name="name" value="ali"></property>
        <property name="phone">
            <bean class="net.wanho.entity.Phone">
                <property name="areaCode" value="025"></property>
                <property name="phoneNumber" value="86187215"></property>
            </bean>
        </property>
</bean>
  • 在src文件夹下创建一个测试类Test.java,关键内容如下:
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml");
        User user0= applicationContext.getBean("user0",User.class);
        User user= applicationContext.getBean("user",User.class);
        Phone phone= applicationContext.getBean("phone",Phone.class);
        System.out.println(user0+user);
        System.out.println(phone);
    或者
        ApplicationContext applicationContext1 = new FileSystemXmlApplicationContext("src:/bean.xml");
        User user= applicationContext.getBean("user1",User.class);
        System.out.println(user.getPhone());

以上就是spring中ioc最基本的配置。

posted @ 2020-03-23 20:49  张力的程序园  阅读(206)  评论(0)    收藏  举报