01 spring中bean的配置与使用
发布日期:2022-03-30 20:19:34 浏览次数:21 分类:博客文章

本文共 1486 字,大约阅读时间需要 4 分钟。

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

1、前提约束

  • 创建一个spring项目

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,内容如下:
  • 在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最基本的配置。

转载地址:https://www.cnblogs.com/alichengxuyuan/p/12554725.html 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:08 配置方式完成事务
下一篇:02 spring中bean的集合的配置和使用

发表评论

最新留言

关注你微信了!
[***.104.42.241]2024年04月15日 04时05分48秒