spring中bean默认都是单例
   singleton  默认值  单例

     容器初始化时(new ClassPathXmlApplicationContext("cn/et/lesson01/prototype/spring.xml"))实例化


<bean id="a" class="cn.et.lesson01.prototype.A" scope="singleton">
	<property name="name" value="zs"></property>
</bean>


测试

package cn.et.lesson01ioc_di;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestCotainer {
    public static void main(String[] args) {
        //创建容器对象
		ApplicationContext context = new ClassPathXmlApplicationContext("cn/et/lesson01ioc_di/spring.xml");
		A a=(A)context.getBean("a");
		A a1=(A)context.getBean("a");
		System.out.println(a==a1);
    }
}



 prototype  多例
        在创建bean的时候 实例化 ------context.getBean()   


<bean id="a" class="cn.et.lesson01.prototype.A" scope="prototype">
	<property name="name" value="zs"></property>
</bean>


测试

package cn.et.lesson01ioc_di;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestCotainer {
    public static void main(String[] args) {
        //创建容器对象
		ApplicationContext context = new ClassPathXmlApplicationContext("cn/et/lesson01ioc_di/spring.xml");
		A a=(A)context.getBean("a");
		A a1=(A)context.getBean("a");
		System.out.println(a==a1);
    }
}




Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐