Noomak
Noomak

Reputation: 371

cannot @Autowired an interface

I'm trying to autowire an interface inside a controller bean

In my context configuration file I've put

<context:annotation-config />

and

<bean id="viewVerbale" class="com.sirfe.controller.VerbaliController" />

my controller class is

@Controller
public class VerbaliController {


    @Autowired
    VerbaliRepository repository;

    private static final Logger logger = LoggerFactory.getLogger(VerbaliController.class);


    @RequestMapping(value = "/sirfe/verbale/{sequVerbale:.+}", method = RequestMethod.GET)
    public ModelAndView viewVerbale(@PathVariable("sequVerbale") String sequVerbale) {

        logger.debug("welcome() - sequVerbale {}", sequVerbale);

        Verbali verbale = repository.findOne(Long.parseLong(sequVerbale));


        ModelAndView model = new ModelAndView();
        model.setViewName("sirfe/verbali/viewVerbale");
        model.addObject("sequVerbale", sequVerbale);

        return model;

    }

}

my interface signature is

public interface VerbaliRepository extends CrudRepository<Verbali, Long>  { }

and when I launch my app I get

 Could not autowire field: com.sirfe.repository.VerbaliRepository com.sirfe.controller.VerbaliController.repository; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.sirfe.repository.VerbaliRepository] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. 

Upvotes: 2

Views: 1976

Answers (2)

Vyncent
Vyncent

Reputation: 1205

Looks like you're trying to use Spring JPA repository.

In order to have Spring create bean for your repository interfaces, you need in applicationContext.xml to declare what package to scan

<jpa:repositories base-package="com.sirfe.repository" />

Doing so, Spring will generate bean implementing the interface for you.

See Spring JPA Repositories

Upvotes: 2

Qwerky
Qwerky

Reputation: 18455

Spring is complaining that it cannot find a valid bean definition that matches, ie there is no bean defined that is an implementation of VerbaliRepository.

You need to define a bean or alternatively annotate an implementation class with @Component eg

<bean id="myRepository" class="com.foo.bar.MyRepository" />

or

@Component
public class MyRepository implements VerbaliRepository {
 ....
}

Upvotes: 0

Related Questions