【问题标题】:Spring MVC xml based config to annotation基于 Spring MVC xml 的配置到注释
【发布时间】:2015-07-11 16:53:09
【问题描述】:

我是 Spring 的新手,正在尝试将基于 xml 的配置转换为基本注释。我阅读了本教程和编码。它与基于 xml 的配置完美配合。 MVC Spring CRUD Tutorial

现在我将所有基于 xml 的配置转换为注释,但我遇到了问题。我读了几乎所有我读过的东西,但我没有解决这个问题。

org.springframework.beans.factory.BeanCreationException:创建名为“personController”的bean时出错:注入自动装配的依赖项失败;嵌套异常是 org.springframework.beans.factory.BeanCreationException:无法自动装配方法:public void com.ulotrix.spring.controller.PersonController.setPersonService(com.ulotrix.spring.service.PersonService);嵌套异常是 org.springframework.beans.factory.NoSuchBeanDefinitionException:没有为依赖找到 [com.ulotrix.spring.service.PersonService] 类型的合格 bean:预计至少有 1 个 bean 有资格作为此依赖的自动装配候选者。依赖注释:{}

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";
}
}

【问题讨论】:

    标签: java xml spring spring-mvc annotations


    【解决方案1】:

    PersonService 定义在包com.ulotrix.spring.services 中,因此将@ComponentScan({ "com.ulotrix.spring.controller" }) 更改为@ComponentScan({ "com.ulotrix.spring" }),这要归功于spring 可以发现包spring 中定义的所有bean。

    【讨论】:

    • 我改成@ComponentScan({ "com.ulotrix.spring" }) 还是一样的错误。我正在使用 Intellij IDEA,这是link bean decleration screenshot。
    • 你的班级 PersonServiceImpl 是用 @Service("personService") 注释的吗?
    • 原来是@Service注解,我改成了Service("personService")。现在它起作用了。现在收到另一个错误。我浏览到http://localhost:8080/persons,错误是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 很高兴它回答了您的问题 :),您可以创建另一个问题并粘贴相应的堆栈跟踪。
    猜你喜欢
    • 2012-01-15
    • 2012-03-23
    • 2015-12-06
    • 1970-01-01
    • 1970-01-01
    • 2010-09-15
    • 1970-01-01
    • 1970-01-01
    • 2016-08-02
    相关资源
    最近更新 更多