spring实操

1.首先创建一个maven工程(使用idea这里就不做演示了)
2. 创建Book类与Author类·
Book 类

public class Book {
    private String bookName;

    private String author;

    public Book(){
        System.out.println("This is Book constructor.");
    }

    public String getBookName() {
        return bookName;
    }

    public void setBookName(String bookName) {
        System.out.println("This is Book setBookName().");
        this.bookName = bookName;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        System.out.println("This is Book setAuthor().");
        this.author = author;
    }

    public void printBookInfo() {
        System.out.println("Book Name:" + this.bookName + ",Author:" + this.author);
    }
}

Author类

public class Author {
    private String name;

    private int age;

    public Author() {
        System.out.println("This is Author constructor.");
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        System.out.println("This is Author setName().");
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        System.out.println("This is Author setAge().");
        this.age = age;
    }

    public void printAuthorInfo() {
        System.out.println("Name:" + this.name + ",Age:" + this.age);
    }
}

3.按照传统方式创建对象:

 public void test1() {
        Book book = new Book();
        book.setAuthor("李四");
        book.setBookName("平凡的世界");

        book.printBookInfo();
    }

执行结果:
在这里插入图片描述
4.使用spring框架注入bean的形式调用:

<?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="bookId" class="com.lize.spring.model.Book">
        <property name="author" value="李四"></property>
        <property name="bookName" value="平凡的世界"></property>
    </bean>
    <bean id="authorId" class="com.lize.spring.model.Author">
        <property name="age" value="26"></property>
        <property name="name" value="李四"></property>
    </bean>

</beans>

5.获取bean实例对象:

 public void getSpring() {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");

        Book book = applicationContext.getBean("bookId", Book.class);
        book.printBookInfo();
    }

6.执行结果:
在这里插入图片描述
运行结果与传统定义方式一样,只是多了一些spring的日志。
在上面的代码中,我们并未使用new运算符来创建Book类的实例,但是却可以得到Book类的实例,这就是Spring的强大之处,所有类的实例的创建都不需要应用程序自己创建,而是交给Spring容器来创建及管理。

7.spring是在什么时候初始化的对象,我们可以打断点调试查看。
在这里插入图片描述
在这里插入图片描述
调试得知在初始化ApplicationContext对象的时候对注入bean的实例进行了初始化,之后在使用的时候直接get即可获取。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章