@scope(“prototype”)无法正常工作

时间:2013-05-17 12:41:51

标签: spring

考虑以下配置

 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>

如果我没有错,它会显示Singleton范围的行为。有人能告诉我为什么它不像“原型”范围那样?

1 个答案:

答案 0 :(得分:4)

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