Spring bean四种的创建方式以及作用域的设置

spring.xml:四种创建方式


<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="food1" class="com.cxl.start.pojo.Food">
        
        <property name="name" value="胡辣汤1">property>
        <property name="price" value="6.0">property>
        <property name="taste" value="hot1">property>
    bean>
    <bean id="food2" class="com.cxl.start.pojo.Food">

        <constructor-arg name="name" value="胡辣汤2">constructor-arg>
        <constructor-arg name="price" value="7">constructor-arg>
        <constructor-arg name="taste" value="SWEET">constructor-arg>
    bean>
    <bean id="foodfactory" class="com.cxl.start.factory.FoodFactory">bean>
    <bean id="food3" factory-bean="foodfactory" factory-method="createFoodBean">

        <property name="name" value="胡辣汤3">property>
        <property name="price" value="8.0">property>
        <property name="taste" value="spicy">property>
    bean>

    <context:component-scan base-package="com.cxl.start">context:component-scan>    
beans>

Food类:

@Data
@NoArgsConstructor
@AllArgsConstructor
@Component
public class Food {
    private String name;
    private Double price;
    private String taste;
}

FoodFactory类:

public class FoodFactory {
    public Food createFoodBean(){
        return new Food();
    }
}

测试类:

public class SpringTest {
    @Test
    public void test(){
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
        Food bean = context.getBean("food3",Food.class);
        System.out.println(bean);
    }
}

作用域的设置:scope


 <bean id="food1" scope="prototype" class="com.cxl.start.pojo.Food">bean>

你可能感兴趣的:(Spring,spring)