Spring 實例化Bean的兩種方式

使用Spring管理Bean也稱依賴注入( Dependency Injection, DI ),經過這種方式將Bean的控制權交給Springjava

在使用Spring實例化一個對象時,不管類是否有參數都會默認調用對象類的無參構造,對於有參數的狀況,Spring有兩種方式能夠帶參實例化spring

示例類 Shapeapp

public class Shape {
    private Integer width;
    private Integer height;

    public Shape() {
        System.out.println("運行了Shape的無參構造");
    }
    
    public Shape(Integer width, Integer height) {
        this.width = width;
        this.height = height;
        System.out.println("運行了Shape的有參構造");
    }

    public Integer getHeight() {
        return height;
    }

    public Integer getWidth() {
        return width;
    }

    public void setHeight(Integer height) {
        this.height = height;
    }

    public void setWidth(Integer width) {
        this.width = width;
    }

    @Override
    public String toString() {
        return "Width: " + this.width + "\tHeight:" + this.height;
    }
}

主函數

public class Demo {
    public static void main(String[] args) {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        Shape shape = (Shape)applicationContext.getBean("Shape");
        System.out.println(shape);
    }
}

applicationContext.xmlide

經過Setter實例化

<?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="Shape" class="learn.test.Shape">
        <!-- property標籤會自動調用Setter   -->
        <property name="width" value="200"></property>
        <property name="height" value="500"></property>
    </bean>
    
</beans>

運行結果函數

運行了Shape的無參構造
Width: 200  Height:500

經過類帶參構造實例化

<?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="Shape" class="learn.test.Shape">
        <!-- constructor-arg標籤調用帶參構造   -->
        <constructor-arg name="width" value="200"></constructor-arg>
        <constructor-arg name="height" value="500"></constructor-arg>
    </bean>
    
</beans>

運行結果:this

運行了Shape的有參構造
Width: 200  Height:500
相關文章
相關標籤/搜索