0

考虑以下配置

 public class MainApp {
        public static void main(String args[]){

            ApplicationContext ac=new ClassPathXmlApplicationContext("src/Beans.xml");
            HelloWorld obj1=(HelloWorld) ac.getBean("helloWorld");
            obj1.setMessage("OBJ1");
            HelloWorld obj2=(HelloWorld) ac.getBean("helloWorld");
            //obj2.setMessage("OBJ2");
            System.out.println(obj1.getMessage());
            System.out.println(obj2.getMessage());
        }
    }

    @Scope("prototype")

    public class HelloWorld {
    String message;
        public String getMessage() {
            return "Your Message:"+message;
        }
        public void setMessage(String message) {
            this.message = message;
        }
        }


    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:context="http://www.springframework.org/schema/context"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
               http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
               http://www.springframework.org/schema/context
               http://www.springframework.org/schema/context/spring-context-3.0.xsd">
               <context:annotation-config />
               <context:component-scan base-package="SpringDemo.src"  />
                 <bean id="helloWorld" class="src.HelloWorld">
           </bean>
          </beans>

如果我没记错的话,它显示的是单例范围的行为。有人可以让我知道为什么它不表现为“原型”范围吗?

4

1 回答 1

4

<bean id="helloWorld" class="src.HelloWorld">在 xml 配置中有这个。如果未指定范围,则scope默认为singleton. xml 配置会覆盖注释。删除 @Scope("prototype")并添加scope="prototype"到 xml。

于 2013-05-17T13:31:46.810 回答