2013-05-29 94 views
1

我的Spring bean與註釋:爲什麼Spring @Autowired ApplicationContext appContext爲null?

@Named 
@Scope("session") 

而這個bean屬性:

@Autowired 
ApplicationContext appContext; 

Spring配置文件中有記入(即其他anotations /注射作品):

<context:component-scan base-package="my.package.name" /> 

爲什麼appContext在這樣的代碼和配置之後爲空?

我想獲得ApplicationContext(以調用getBean(...)),這可能是相當複雜的任務(從其他討論判斷)在以前的Spring版本(例如,需要獲得Spring Web中的ServletContext應用程序創建ApplicationContext並獲取ServletContext對於不直接訪問HTTP請求對象的bean來說可能是相當複雜的任務)。在Spring 3.x中,據我所知,可以使用簡單的@Autwired注入。如何訪問AppContext?

+0

而不是使用應用程序上下文更好地使用@Autowired來注入/獲取bean –

回答

2

這裏第一個問題是您使用的是@Named這是Java EE註釋,而據我所知,Spring尚未支持Java EE註釋。因此,不要使用@Named嘗試使用Spring註釋@Service,@Component,@Repository等。

下面是您的示例我已經使用JSF託管bean以及如何集成bean。

@ManagedBean(name="myBacking") 
@RequestScoped 
public class MyBacking { 

    private String myText; 

    @ManagedProperty(value="#{mySpring}") 
    MySpringBean mySpring; 

    public String getMyText() { 
     myText = mySpring.getText(); 
     return myText; 
    } 

    public void setMyText(String myText) { 
     this.myText = myText; 
    } 

    public MySpringBean getMySpring() { 
     return mySpring; 
    } 

    public void setMySpring(MySpringBean mySpring) { 
     this.mySpring = mySpring; 
    } 


} 

@Service("mySpring") 
@Scope("request") 
public class MySpringBean { 

    @Autowired 
    MySecond mySecond; 

    public String getText(){ 
     return "Hello KP" + mySecond.appObj(); 
    } 

} 


@Service 
@Scope("request") 
public class MySecond { 

    @Autowired 
    ApplicationContext applicationContext; 

    public String appObj(){ 
     MyThrid mythird =(MyThrid)applicationContext.getBean("myThrid"); 
     return "My Second Bean calld "+ mythird.getTxt(); 
    } 
} 

@Service 
public class MyThrid { 

    public String getTxt(){ 
     return "from thrid Bean"; 
    } 
}