Spring(IOC创建对象的方式)

导入依赖

  <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.3.10</version>
        </dependency>

使用无参创建对象,默认

pojo

public class Hello {
    
    
    private String str;

    public Hello() {
    
        
    }
    public String getStr() {
    
    
        return str;
    }
    public void setStr(String str) {
    
    
        this.str = str;
    }
    @Override
    public String toString() {
    
    
        return "Hello{" +
                "str='" + str + '\'' +
                '}';
    }
}

applicationContext.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">
<!--
使用Spring来创建对象,在Spring这些都成为Bean
    bean 就是一个对象,Spring以Ioc为基础进行封装
    类型 变量名=new 类型();
    Hello hello=new Hello();
    id = 变量名
    class = new 的对象
    property 相当于给对象中的属性设置一个值
-->
<bean id="hello" class="com.my.pjo.Hello">
    <!--
    ref:引用Spring容器中创建好的对象
    value:具体的值,基本数据类型-->
    <property name="str" value="Andrew"/>
</bean>
</beans>

Test

context中的xml可以有多个。

    @Test
    public void Test1(){
    
    
    //ApplicationContext: 建议用ApplicationContext 
     ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        Object hello = context.getBean("hello");
        System.out.println(hello);
    }

有参创建对象

package com.my.pjo;

public class Hello {
    
    
    private String str;
    
    public Hello(String str) {
    
    
        this.str = str;
    }
    public String getStr() {
    
    
        return str;
    }
    public void setStr(String str) {
    
    
        this.str = str;
    }
    @Override
    public String toString() {
    
    
        return "Hello{" +
                "str='" + str + '\'' +
                '}';
    }
}

applicationContext.xml

构造器创建方式:
1.下标赋值

<bean id="hello" class="com.my.pjo.Hello">
  <constructor-arg index="0" value="Andrew"/>
</bean>

2.类型(不推荐)

<bean id="hello" class="com.my.pjo.Hello">
    <constructor-arg type="java.lang.String" value="Andrew"/>
</bean>

3.参数名(推荐)

<bean id="hello" class="com.my.pjo.Hello">
    <constructor-arg name="str" value="Andrew"/>
</bean>

总结:无参默认property,有参用构造器。
在配置文件加载的时候,容器中管理的对象已经初始化了。

おすすめ

転載: blog.csdn.net/fhuqw/article/details/121274298