@Autowired字段获取null

时间:2013-08-06 22:58:40

标签: spring spring-mvc

我有我的类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());
    }
}

DAO

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();
    }

}

根context.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>

提前致谢

1 个答案:

答案 0 :(得分:4)

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