如何创建可以使用注释自动装配的spring bean?

时间:2011-04-29 14:17:03

标签: java spring annotations

我有一个小型MVC网络应用程序,其中使用注释配置了控制器。

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]类型的匹配bean

我尝试过向ScritTagsJSView添加组件注释

@Component("scriptTagsJSView")
public class ScriptTagsJSView implements View {
没有运气。我还尝试添加配置POJO并使用@Bean注释

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

我可能错过了一些相当简单的东西,但我不明白为什么这不起作用。有什么想法吗?

2 个答案:

答案 0 :(得分:2)

我认为你的xml可能只需要<context:annotation-config/>

答案 1 :(得分:2)

首先,您要使用注释驱动标记。 这将确保Spring实例化所有注释的类 @Controller,@ Repository,@ Service和@Component

<mvc:annotation-driven />

您还需要组件扫描,但您已经拥有它。

您可能还想避免为您的Beans命名,因为spring会根据类型进行匹配。 (不要使用@Component(“scriptTagsJSView”),而只使用@Component)

最后,您需要在需要注射的位置添加@Autowired。 我个人只将它与构造函数结合使用。

public class JSDependencyController {
   @Autowired
   public JSDependencyController(ScriptTagsJSView view){
      this.view = view;
   }
}