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即可獲取。