1. 程式人生 > 其它 >spring5入門(三):基於xml配置進行bean管理

spring5入門(三):基於xml配置進行bean管理

  • Bean管理操作有兩種方式
(1)基於 xml 配置檔案方式實現
(2)基於註解方式實現
  • 基於xml配置
# 在src路徑下編寫bean.xml
<bean id="user" class="com.ychen.spring.User"></bean>

# 使用 bean 標籤,標籤裡面新增對應屬性,就可以實現物件建立
# 在 bean 標籤有很多屬性
  * id 屬性:唯一標識
  * class 屬性:類全路徑
# 建立物件時,預設執行無引數構造方法完成物件建立

# 最後通過如下方式獲取物件
ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
User user = context.getBean("user", User.class);
  • 基於xml注入屬性
DI:依賴注入,就是注入屬性
  • 在實體類中使用set方法注入
# 新建1個實體類Book
public class Book {

    private String bname;

    private String bauthor;

    public void setBname(String bname) {
        this.bname = bname;
    }

    public void setBauthor(String bauthor) {
        this.bauthor = bauthor;
    }

    // main方法中測試注入屬性
    public static void main(String[] args) {
        Book book = new Book();
        book.setBauthor("goudan");
        System.out.println(book);
    }

}

# main方法中測試
com.ychen.spring.model.Book@5b464ce8

Process finished with exit code 0
  • 基於xml配置注入屬性
# 編寫實體類
public class Book {

    private String bname;

    private String bauthor;

    private String address;

    public void setBname(String bname) {
        this.bname = bname;
    }
    public void setBauthor(String bauthor) {
        this.bauthor = bauthor;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public void testDemo() {
        System.out.println(bname+"::"+bauthor+"::"+address);
    }

}

# 編寫bean.xml
    <bean id="book" class="com.ychen.spring.model.Book">
        <property name="bname" value="易筋經"></property>
        <property name="bauthor" value="達摩老祖"></property>
    </bean>

# 編寫測試方法
    @Test
    public void testBook1() {
        ApplicationContext context =
                new ClassPathXmlApplicationContext("bean1.xml");
        Book book = context.getBean("book", Book.class);
        System.out.println(book);
        book.testDemo();
    }

# 測試
com.ychen.spring.model.Book@2cb4893b
易筋經::達摩老祖::null