【3】IOC创建对象的方式
程序员文章站
2022-07-15 10:23:34
...
4、IOC创建对象的方式
4.1、通过无参构造方法来创建
-
Teacher.java
public class Teacher { private String name; public Teacher() { System.out.println("Teacher对象默认被创建"); } public String getName() { return name; } public void setName(String name) { this.name = name; } public void show(){ System.out.println("name="+name); } }
-
beans.xml
<?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="teacher" class="com.kuber.pojo.Teacher" name="teacher2"> <property name="name" value="工藤静香真好看"/> </bean> </beans>
-
测试类
@Test public void test1(){ ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml"); Teacher teacher = (Teacher) context.getBean("teacher2"); teacher.show(); }
-
输出效果
4.2、通过有参方法来构造
-
User.java
public class User { private String name; public User(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } public void show(){ System.out.println("name="+name); } }
-
beans.xml
<?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 https://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="user" class="com.kuber.pojo.User"> <!--<constructor-arg index="0" value="工藤静香"/>--> <constructor-arg name="name" value="工藤静香"/> </bean> </beans>
其中constructor-arg有三种配置方式
<!-- 第一种根据index参数下标设置 --> <bean id="user" class="com.kuang.pojo.User"> <!-- index指构造方法 , 下标从0开始 --> <constructor-arg index="0" value="工藤静香"/> </bean> <!-- 第二种根据参数名字设置 --> <bean id="user" class="com.kuang.pojo.User"> <!-- name指参数名 --> <constructor-arg name="name" value="工藤静香"/> </bean> <!-- 第三种根据参数类型设置 --> <bean id="user" class="com.kuang.pojo.User"> <constructor-arg type="java.lang.String" value="工藤静香"/> </bean>
-
测试
@Test public void test1(){ ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml"); User user = context.getBean("user", User.class); user.show(); }
-
结果
结论:在配置文件加载的时候,其中管理的对象都已经开始初始化了。
上一篇: 依赖注入(DI)
下一篇: spring 常用注解