2

我的类 Categoria 有这个属性编辑器,我试图将它自动连接到服务,问题在于服务不断获得空值。此外,这似乎是孤立的,或者至少我是这么认为的,因为我在控制器上自动连接了同一类的字段,所以我不知道发生了什么,我已经遇到了这样的错误,但是在那个时候它根本不起作用。

转换器

package com.carloscortina.paidosSimple.converter;

import java.beans.PropertyEditorSupport;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.carloscortina.paidosSimple.model.Categoria;
import com.carloscortina.paidosSimple.service.CategoriaService;

public class CategoriaConverter extends PropertyEditorSupport{

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

    @Autowired
    private CategoriaService categoriaService;

    @Override
    public void setAsText(String categoria) {

        logger.info(categoria);
        Categoria cat = new Categoria();
        cat = categoriaService.getCategoria(Integer.parseInt(categoria));
        setValue(cat);
    }


}

服务

package com.carloscortina.paidosSimple.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.carloscortina.paidosSimple.dao.CategoriaDao;
import com.carloscortina.paidosSimple.model.Categoria;

@Service
@Transactional
public class CategoriaServiceImpl implements CategoriaService{

    @Autowired
    private CategoriaDao categoriaDao;

    @Override
    public Categoria getCategoria(int id) {
        // TODO Auto-generated method stub
        return categoriaDao.getCategoria(id);
    }

    @Override
    public List<Categoria> getCategorias() {
        return categoriaDao.getCategorias();
    }

}

在这里它确实有效

控制器

package com.carloscortina.paidosSimple.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.carloscortina.paidosSimple.converter.CategoriaConverter;
import com.carloscortina.paidosSimple.model.Categoria;
import com.carloscortina.paidosSimple.model.Personal;
import com.carloscortina.paidosSimple.model.Usuario;
import com.carloscortina.paidosSimple.service.CategoriaService;
import com.carloscortina.paidosSimple.service.PersonalService;
import com.carloscortina.paidosSimple.service.UsuarioService;

@Controller
public class PersonalController {

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

    @Autowired
    private PersonalService personalService;

    @Autowired
    private UsuarioService usuarioService;

    @Autowired
    private CategoriaService categoriaService;

    @RequestMapping(value="/usuario/add")
    public ModelAndView addUsuarioPage(){
        ModelAndView modelAndView = new ModelAndView("add-usuario-form");
        modelAndView.addObject("categorias",categorias());
        modelAndView.addObject("user", new Usuario());
        return modelAndView;
    }

    @RequestMapping(value="/usuario/add/process",method=RequestMethod.POST)
    public ModelAndView addingUsuario(@ModelAttribute Usuario user){
        ModelAndView modelAndView = new ModelAndView("add-personal-form");
        usuarioService.addUsuario(user);
        logger.info(modelAndView.toString());
        String message= "Usuario Agregado Correctamente.";
        modelAndView.addObject("message",message);
        modelAndView.addObject("staff",new Personal());

        return modelAndView;
    }

    @RequestMapping(value="/personal/list")
    public ModelAndView listOfPersonal(){
        ModelAndView modelAndView = new ModelAndView("list-of-personal");

        List<Personal> staffMembers = personalService.getAllPersonal();
        logger.info(staffMembers.get(0).getpNombre());
        modelAndView.addObject("staffMembers",staffMembers);

        return modelAndView;
    }

    @RequestMapping(value="/personal/edit/{id}",method=RequestMethod.GET)
    public ModelAndView editPersonalPage(@PathVariable int id){
        ModelAndView modelAndView = new ModelAndView("edit-personal-form");
        Personal staff = personalService.getPersonal(id);
        logger.info(staff.getpNombre());
        modelAndView.addObject("staff",staff);

        return modelAndView;
    }

    @RequestMapping(value="/personal/edit/{id}", method=RequestMethod.POST)
    public ModelAndView edditingPersonal(@ModelAttribute Personal staff, @PathVariable int id) {

        ModelAndView modelAndView = new ModelAndView("home");

        personalService.updatePersonal(staff);

        String message = "Personal was successfully edited.";
        modelAndView.addObject("message", message);

        return modelAndView;
    }

    @RequestMapping(value="/personal/delete/{id}", method=RequestMethod.GET)
    public ModelAndView deletePersonal(@PathVariable int id) {
        ModelAndView modelAndView = new ModelAndView("home");
        personalService.deletePersonal(id);
        String message = "Personal was successfully deleted.";
        modelAndView.addObject("message", message);
        return modelAndView;
    }

    private Map<String,String> categorias(){
        List<Categoria> lista = categoriaService.getCategorias();

        Map<String,String> categorias = new HashMap<String, String>();
        for (Categoria categoria : lista) {
            categorias.put(Integer.toString(categoria.getId()), categoria.getCategoria());
        }
        return categorias;
    }

    @InitBinder
    public void initBinderAll(WebDataBinder binder){
        binder.registerCustomEditor(Categoria.class, new CategoriaConverter());
    }
}

package com.carloscortina.paidosSimple.dao;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.carloscortina.paidosSimple.converter.CategoriaConverter;
import com.carloscortina.paidosSimple.model.Categoria;

@Repository
public class CategoriaDaoImp implements CategoriaDao {

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

    @Autowired
    private SessionFactory sessionFactory;

    private Session getCurrentSession(){
        return sessionFactory.getCurrentSession();
    }

    @Override
    public Categoria getCategoria(int id) {

        Categoria rol = (Categoria) getCurrentSession().get(Categoria.class, id);
        if(rol == null) {
            logger.debug("Null");
        }else{
            logger.debug("Not Null");
        }
        logger.info(rol.toString());
        return rol;
    }

    @Override
    @SuppressWarnings("unchecked")
    public List<Categoria> getCategorias() {
        // TODO Auto-generated method stub
        return getCurrentSession().createQuery("from Categoria").list();
    }

}

根上下文.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:jee="http://www.springframework.org/schema/jee"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">

    <!-- Root Context: defines shared resources visible to all other web components -->

    <!-- Enable transaction Manager -->
    <tx:annotation-driven/>

    <!-- DataSource JNDI -->
    <jee:jndi-lookup id="dataSource" jndi-name="jdbc/paidos" resource-ref="true" />

    <!--  Session factory -->
    <bean id="sessionFactory" 
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" 
        p:dataSource-ref="dataSource"
        p:hibernateProperties-ref="hibernateProperties"
        p:packagesToScan="com.carloscortina.paidosSimple.model" />

    <!--  Hibernate Properties -->
    <util:properties id="hibernateProperties">
        <prop key="hibernate.dialect">
            org.hibernate.dialect.MySQL5InnoDBDialect
        </prop>
        <prop key="hibernate.show_sql">false</prop>
    </util:properties>

    <bean id="transactionManager"
        class="org.springframework.orm.hibernate4.HibernateTransactionManager"
        p:sessionFactory-ref="sessionFactory" />

    <context:annotation-config />
    <context:component-scan base-package="com.carloscortina.paidosSimple,com.carlosocortina.paidosSimple.converter,com.carlosocortina.paidosSimple.service,com.carlosocortina.paidosSimple.dao" />

</beans>

提前致谢

4

1 回答 1

4

您正在PropertyEditor使用 new 运算符 () 创建外部弹簧上下文,binder.registerCustomEditor(Categoria.class, new CategoriaConverter());因此不会注入服务:按照此链接上的指南解决您的问题。

于 2013-08-07T01:13:08.283 回答