简体   繁体   English

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

[英]How to create spring bean that can be autowired using annotations?

I've got a small MVC web app with the Controller configured using annotations.我有一个小型 MVC web 应用程序,其中 Controller 使用注释配置。

The xml setup is simple. 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>

My controller looks like我的 controller 看起来像

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

    @Autowired
    private ScriptTagsJSView scriptTagsJSView;

I'm getting an error saying我收到一条错误消息

No matching bean of type [net.dynamic_tools.jsdependency.view.ScriptTagsJSView] found for dependency没有为依赖项找到类型为 [net.dynamic_tools.jsdependency.view.ScriptTagsJSView] 的匹配 bean

I've tried adding a component annotation to ScritTagsJSView我尝试向 ScritTagsJSView 添加组件注释

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

with no luck.没有运气。 I've also tried adding a configuration POJO and using the @Bean annotation我还尝试添加配置 POJO 并使用 @Bean 注释

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

I'm probably missing something fairly simple, but I can't see why this isn't working.我可能遗漏了一些相当简单的东西,但我不明白为什么这不起作用。 Any ideas?有任何想法吗?

I think you might just need <context:annotation-config/> in your xml.我认为您可能只需要在 xml 中使用<context:annotation-config/>

First of all you want to use the annotation-driven tag.首先,您要使用注释驱动标签。 This will make sure Spring instantiates all classes annotated with @Controller, @Repository, @Service and @Component这将确保 Spring 实例化所有使用 @Controller、@Repository、@Service 和 @Component 注释的类

<mvc:annotation-driven />

You also need the component scan but you already have it.您还需要组件扫描,但您已经拥有它。

You might also want to refrain from giving names to your Beans as spring will just match based on types.您可能还想避免为您的 Bean 命名,因为 spring 将仅根据类型进行匹配。 (do not use @Component("scriptTagsJSView") but just @Component) (不要使用@Component("scriptTagsJSView") 而只是@Component)

Finally you need to add @Autowired where you need injecting.最后,您需要在需要注入的地方添加@Autowired。 Personally i only use it in combination with constructors.我个人只将它与构造函数结合使用。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM