其他分享
首页 > 其他分享> > spring5入门(三):基于xml配置进行bean管理

spring5入门(三):基于xml配置进行bean管理

作者:互联网

(1)基于 xml 配置文件方式实现
(2)基于注解方式实现
# 在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);
DI:依赖注入,就是注入属性
# 新建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
# 编写实体类
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

标签:xml,String,bauthor,bname,bean,Book,public,spring5
来源: https://www.cnblogs.com/chniny/p/16154987.html