1

I am new at Spring and trying to xml based config to annotation basic. I read this tutorial amd coded. It works perfect with xml based config. MVC Spring CRUD Tutorial

And now I converted all xml based config to annotation but I have a problem. I ried almost everything what I read but I didn't solve this problem.

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'personController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void com.ulotrix.spring.controller.PersonController.setPersonService(com.ulotrix.spring.service.PersonService); nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.ulotrix.spring.service.PersonService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}

AppConfig.java

@EnableWebMvc
@Configuration
@ComponentScan({ "com.ulotrix.spring.controller" })
public class AppConfig extends WebMvcConfigurerAdapter {

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}

@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
    configurer.enable();
}

@Bean
public SessionFactory sessionFactory() {

    LocalSessionFactoryBuilder builder = new LocalSessionFactoryBuilder(dataSource());
    builder.scanPackages("com.ulotrix.spring.model");
    builder.addProperties(getHibernationProperties());

    return builder.buildSessionFactory();
}

private Properties getHibernationProperties() {

    Properties prop = new Properties();
    prop.put("hibernate.format_sql", "true");
    prop.put("hibernate.show_sql", "true");
    prop.put("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");

    return prop;
}

@Bean(name = "dataSource")
public BasicDataSource dataSource() {

    BasicDataSource ds = new BasicDataSource();
    ds.setDriverClassName("com.mysql.jdbc.Driver");
    ds.setUrl("jdbc:mysql://localhost:3306/deneme_db2");
    ds.setUsername("root");
    ds.setPassword("xxx");

    return ds;
}

@Bean
public HibernateTransactionManager txManger() {
    return new HibernateTransactionManager(sessionFactory());
}

@Bean
public InternalResourceViewResolver viewResolver() {
    InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
    viewResolver.setViewClass(JstlView.class);
    viewResolver.setPrefix("/WEB-INF/views/");
    viewResolver.setSuffix(".jsp");
    return viewResolver;
}

}

SpringMVCInitializer.java

public class SpringMvcInitializer implements WebApplicationInitializer {

@Override
public void onStartup(ServletContext container) {
    // Create the 'root' Spring application context
    AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
    rootContext.register(AppConfig.class);

    // Manage the lifecycle of the root application context
    container.addListener(new ContextLoaderListener(rootContext));

    // Create the dispatcher servlet's Spring application context
    AnnotationConfigWebApplicationContext dispatcherServlet = new AnnotationConfigWebApplicationContext();
    dispatcherServlet.register(AppConfig.class);

    // Register and map the dispatcher servlet
    ServletRegistration.Dynamic dispatcher = container.addServlet("dispatcher", new DispatcherServlet(dispatcherServlet));
    dispatcher.setLoadOnStartup(1);
    dispatcher.addMapping("/");

}

}

PersonController.java

@Controller
public class PersonController {

private PersonService personService;

@Autowired(required = true)
@Qualifier(value = "personService")
public void setPersonService(PersonService ps) {
    this.personService = ps;
}

@RequestMapping(value = "/persons", method = RequestMethod.GET)
public String listPersons(Model model) {
    model.addAttribute("person", new Person());
    model.addAttribute("listPersons", this.personService.listPersons());
    return "person";
}

//For add and update person both
@RequestMapping(value = "/person/add", method = RequestMethod.POST)
public String addPerson(@ModelAttribute("person") Person p) {

    if(p.getId() == 0) {
        this.personService.addPerson(p);
    }else {
        this.personService.updatePerson(p);
    }
    return "redirect:/persons";
}

@RequestMapping(value = "/remove/{id}")
public String removePerson(@PathVariable("id") int id) {

    this.personService.removePerson(id);
    return "redirect:/persons";
}

@RequestMapping(value = "/edit/{id}")
public String editPerson(@PathVariable("id") int id, Model model) {
    model.addAttribute("person", this.personService.getPersonById(id));
    model.addAttribute("listPersons", this.personService.listPersons());
    return "person";
}
}

1 Answer 1

1

The PersonService is defined in package com.ulotrix.spring.services, so change @ComponentScan({ "com.ulotrix.spring.controller" }) to @ComponentScan({ "com.ulotrix.spring" }) thanks to which spring can discover all the beans defined inside package spring.

Sign up to request clarification or add additional context in comments.

4 Comments

I changed to @ComponentScan({ "com.ulotrix.spring" }) and still same error. I am using Intellij IDEA and this is link bean decleration screenshot.
Is your class PersonServiceImpl annotated with @Service("personService") ?
It was @Service annotation and I changed to Service("personService"). Now it works. And now receive another error. I am browse to http://localhost:8080/persons and error is SEVERE: Servlet.service() for servlet [dispatcher] in context with path [] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause
@ulotrix Glad it answers your question :) , you can create another question and paste the appropriate stacktrace.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.