1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > [Spring5]IOC容器_Bean管理XML方式_创建对象_set注入属性and有参构造注入属性

[Spring5]IOC容器_Bean管理XML方式_创建对象_set注入属性and有参构造注入属性

时间:2019-12-26 06:12:18

相关推荐

[Spring5]IOC容器_Bean管理XML方式_创建对象_set注入属性and有参构造注入属性

IOC操作 Bean管理

什么是Bean管理

1.Bean管理指的是两个操作:

a.Spring创建对象

b.Spring注入属性

2.Bean管理操作有两种方式

a.基于xml配置文件方式实现

b.基于注解方式实现

IOC操作Bean管理(基于xml方式)

1.基于xml方式创建对象

<!--配置User对象创建--><bean id = "user" class = "com.atguigu.spring.User"></bean>

a.在spring配置文件中,使用bean标签,标签里面添加对应属性,就可以实现对象创建

b.在bean标签有很多属性,介绍常用的属性

i.id属性:唯一标识

ii.class属性:类全路径(包类路径)

2.基于xml方式注入属性

3.创建对象的时候,默认执行无参构造方法完成对象创建

2.基于xml方式注入属性

a.DI:依赖注入,就是注入属性

i.第一种注入方式:使用set方法进行注入

(1)创建类,定义属性和对应的set方法

package com.atguigu.spring;/*** 演示使用set方法进行注入属性*/public class Book {private String bname;private String bauthor;public String getBname() {return bname;}public void setBname(String bname) {this.bname = bname;}public String getBauthor() {return bauthor;}public void setBauthor(String bauthor) {this.bauthor = bauthor;}public void testDemo(){System.out.println(bname + "::" + bauthor);}}

(2)在spring配置文件配置对象创建,配置属性注入

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="/schema/beans"xmlns:xsi="/2001/XMLSchema-instance"xsi:schemaLocation="/schema/beans /schema/beans/spring-beans.xsd"><!-- &lt;!&ndash;配置User对象创建&ndash;&gt;--><!-- <bean id = "user" class = "com.atguigu.spring.User"></bean>--><!--set方法注入属性--><bean id = "book" class = "com.atguigu.spring.Book"><!--使用property完成属性注入--><property name="bname" value="易筋经"></property><property name="bauthor" value="达摩老祖"></property></bean></beans>

(3)测试

public class TestSpring05 {@Testpublic void testAdd(){ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");Book book = context.getBean("book", Book.class);System.out.println(book);book.testDemo();}}

ii.第二种注入方式:使用有参构造方法进行注入

(1)创建类,定义属性,创建属性对应有参数构造方法

package com.atguigu.spring;/*** 使用有参数构造注入*/public class Orders {private String name;private String address;public Orders(String name,String address){this.name = name;this.address = address;}public void orderTest(){System.out.println(name + " - "+address);}}

(2)在spring配置文件中进行配置

<bean id = "order" class = "com.atguigu.spring.Orders"><constructor-arg name = "name" value = "电脑"></constructor-arg><constructor-arg name = "address" value = "China"></constructor-arg></bean>

(3)测试

package com.atguigu.test;import com.atguigu.spring.User;import javafx.application.Application;import org.junit.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import com.atguigu.spring.Orders;public class TestSprindAdd {@Testpublic void testOrder(){//1.加载spring配置文件ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");//2.获取配置创建的对象Orders orders = context.getBean("order", Orders.class);System.out.println(orders);orders.orderTest();}}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。