2011-04-29 97 views
2

我有一個小的MVC web應用程序,使用註釋配置了控制器。如何創建使用註釋可以自動裝配的spring bean?

xml設置很簡單。

<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.xsd 
         http://www.springframework.org/schema/context 
         http://www.springframework.org/schema/context/spring-context.xsd"> 

<context:component-scan base-package="net.dynamic_tools.jsdependency" /> 
</beans> 

我的控制器看起來像

@Controller 
@RequestMapping("/*") 
public class JSDependencyController { 

    @Autowired 
    private ScriptTagsJSView scriptTagsJSView; 

我收到一個錯誤說

類型的無匹配豆[net.dynamic_tools.jsdependency.view.ScriptTagsJSView]發現依賴

我試過向Scr添加組件註釋itTagsJSView

@Component("scriptTagsJSView") 
public class ScriptTagsJSView implements View { 

沒有運氣。我也嘗試添加的配置POJO和使用@Bean註釋

@Configuration 
public class Config { 
    @Bean 
    public ScriptTagsJSView getScriptTagsJSView() { 
     return new ScriptTagsJSView(); 
} 

我可能失去了一些東西很簡單,但我不明白爲什麼這是行不通的。有任何想法嗎?

+0

ScriptTagsJSView在哪個包中?組件掃描基本包僅從您指定的包向下搜索,因此如果該類在該包外部,則不會被掃描。編輯:看到我的答案下面,但也考慮上面的評論。 – Jberg 2011-04-29 14:23:55

+0

感謝您的輸入。欣賞努力。原來問題是我是一個白癡。我認爲它使用的xml文件不是它實際使用的xml文件。它實際使用的是從net.dynamic_tools.jsdependency.controller進行掃描,因此在net.dynamic_tools.jsdependency.view中缺少註釋。註釋配置似乎並不需要。 – 2011-04-30 05:01:02

+1

對於任何想要做這件事的人來說,@Component註解就是我的工作。我刪除了@Configuration和@Bean類。 – 2011-04-30 05:03:20

回答

2

我想你可能只需要在你的xml中使用<context:annotation-config/>

2

首先,您要使用註釋驅動標籤。 這將確保春季實例與 @Controller,@Repository,@Service和@Component

<mvc:annotation-driven /> 

註釋您還需要組件掃描,但你已經擁有它的所有類。

你可能也想避免給你的豆名稱,因爲春天只是基於類型匹配。 (不要使用@Component(「scriptTagsJSView」)而只是@Component)

最後,您需要在需要注入的地方添加@Autowired。 我個人僅將它與構造函數結合使用。

public class JSDependencyController { 
    @Autowired 
    public JSDependencyController(ScriptTagsJSView view){ 
     this.view = view; 
    } 
} 
相關問題