0
点赞
收藏
分享

微信扫一扫

Spring-HelloWorld

爱做梦的夏夏 2022-03-30 阅读 41
mavenjavajar
  1. 创建一个普通的Maven项目,然后引入spring-context依赖

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>5.1.9.RELEASE</version>
    </dependency>
    
  2. 在resources目录下创建一个spring的配置文件,命名为ApplicationContext.xml
    在这里插入图片描述

  3. 在ApplicationContext.xml中的结构体中,添加

    <bean class = "org.example.Book" id = "book" />
    

    通过反射机制,创建一个Book类对象交给Bean容器。

  4. 可以在其他类中,通过以下两种方式获得配置文件

    //通过当前resources的相对路径获取
    ClassPathXmlApplicationContext ctx1 = new ClassPathXmlApplicationContext("applicationContext.xml");
    //通过绝对路径获取
    FileSystemXmlApplicationContext ctx2 = new FileSystemXmlApplicationContext("E:\\workspace\\IdeaProjects\\example-springHelloWorld\\src\\main\\resources\\applicationContext.xml");
    
  5. 可以通过以下方法使用对象

    Book book1 = (Book) ctx1.getBean("book");
    Book book2 = ctx1.getBean("book", Book.class);
    Book book3 = ctx1.getBean(Book.class);//当且仅当<Beans></Beans>中只有一个Book对象时可使用
    
举报

相关推荐

0 条评论