Programming Guy
Programming Guy

Reputation: 7441

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.

The xml setup is simple.

<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
@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

I've tried adding a component annotation to ScritTagsJSView

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

with no luck. I've also tried adding a configuration POJO and using the @Bean annotation

@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?

Upvotes: 2

Views: 6836

Answers (2)

G-Man
G-Man

Reputation: 1331

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

<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. (do not use @Component("scriptTagsJSView") but just @Component)

Finally you need to add @Autowired where you need injecting. Personally i only use it in combination with constructors.

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

Upvotes: 2

Jberg
Jberg

Reputation: 945

I think you might just need <context:annotation-config/> in your xml.

Upvotes: 2

Related Questions