spring::ioc作用域

Bean 的作用域

singleton

单实例

prototype

多实例,每次都是新建一个prototype,

 <!--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-3.0.xsd">

   <bean id="helloWorld" class="com.tutorialspoint.HelloWorld" 
      scope="prototype">
  <!--定义作用域是多实例-->
   </bean>
</beans>
//实现
public static void main(String[] args) {
      ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
      HelloWorld objA = (HelloWorld) context.getBean("helloWorld");
      objA.setMessage("I'm object A");
      objA.getMessage();
      HelloWorld objB = (HelloWorld) context.getBean("helloWorld");
      objB.getMessage();
   }
//输出:I'm object A
      null
posted @ 2022-11-26 23:53  壹剑霜寒十四州  阅读(17)  评论(0编辑  收藏  举报