2013-05-17 53 views
0

考慮以下配置@Scope(「原型」)不能正常工作

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> 

如果我沒看錯的是呈現出辛格爾頓範圍的行爲。有人能讓我知道爲什麼它不像「原型」範圍那樣行事嗎?

+0

class name'src.HelloWorld' is wrong。您不需要將'src'目錄指定爲'package' –

+0

如果我刪除它,它將顯示錯誤無法在類路徑資源[src/Beans.xml]中定義名稱爲'helloWorld'的bean的類[HelloWorld] ;我得到的輸出,但它的單身作用域,而不是原型 – Aashish

+0

@Aashish你看到的行爲究竟是什麼? – soulcheck

回答

4

您在xml配置中有這<bean id="helloWorld" class="src.HelloWorld">。當沒有指定範圍時,scope默認爲singleton。 xml配置會覆蓋註釋。刪除@Scope("prototype")並在xml中添加scope="prototype"

+0

但葉夫根,我想用註解 – Aashish

+0

定義範圍然後僅使用註釋和刪除XML bean定義 –

+0

如果我正在刪除它,我得到一個錯誤異常在線程「主」org.springframework.beans.factory.NoSuchBeanDefinitionException:沒有bean名爲'helloWorld'被定義 – Aashish