복붙노트

[SPRING] Spring 관리 빈에서 @ManagedProperty가 null입니다.

SPRING

Spring 관리 빈에서 @ManagedProperty가 null입니다.

매니지드 프로퍼티를 정의하여 다른 매니 폴드 빈에 인젝션 빈을 주입하는 데 어려움이 있습니다. 나는 3 일 동안 googling하고 stackoverflowing하고 있지만 결과는 없다.

나는 이클립스 4.2로 개발 중이며 통합 된 Tomcat 7에 배치하고있다.

그래서, 아무도 왜 내 재산이 null인지 말해 줄 수 있습니까?

Pom.hml

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <spring.version>3.0.5.RELEASE</spring.version>
        <java.version>1.6</java.version>
    </properties>    
<dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-expression</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-orm</artifactId>
        <version>${spring.version}</version>
        <type>jar</type>
        <scope>compile</scope>
    </dependency>

을 포함한다.

    <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" 
    http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/applicationContext*.xml</param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

@Autowired 주석을 스캔하기 위해 bean을 applicationContext에 설정했다. (예, bean을 사용하지 않고 applicationContext에서 시도했지만 ManagedProperty도 설정되지 않습니다.)

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.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-3.0.xsd">

<context:annotation-config />

<context:component-scan base-package="myPackage" />

<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>

<bean class="myPackage.dao.UserDao" id="userDao" />
<bean class="myPackage.dao.WorldDao" id="worldDao" />
<bean class="myPackage.dao.BuildingTypeDao" id="buildingTypeDao" />
<bean class="myPackage.dao.BuffTypeDao" id="buffTypeDao" />
<bean class="myPackage.dao.ClanDao" id="clanDao" />

<bean class="myPackage.bean.MainBean" id="mainBean" />
<bean class="myPackage.bean.UserBean" id="userBean" />
<bean class="myPackage.bean.AdminBean" id="adminBean" />

메인 빈

package myPackage.bean;
import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import myPackage.model.MainModel;

@ManagedBean
@SessionScoped
public class MainBean implements Serializable {

private static final long serialVersionUID = 1L;

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

private MainModel model;

/**
 * @return the model
 */
public MainModel getModel() {
    if (model == null) {
        model = new MainModel();
    }
    return model;
}

/**
 * @param model the model to set
 */
public void setModel(MainModel model) {
    this.model = model;
    }
}

UserBean

package myPackage.bean;

import java.io.Serializable;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;

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

import myPackage.dao.UserDao;
import myPackage.entity.User;

@ManagedBean
@RequestScoped
public class UserBean implements Serializable {

private static final long serialVersionUID = 1L;

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

@ManagedProperty(value="#{mainBean}")
private MainBean mainBean;

@Autowired
private UserDao userDao;

/**
 * @return the mainBean
 */
public MainBean getMainBean() {
    return mainBean;
}

/**
 * @param mainBean the mainBean to set
 */
public void setMainBean(MainBean mainBean) {
    this.mainBean = mainBean;
}

public String doLogin() {
    User user = userDao.getUserByUsernameAndPassword(getMainBean().getModel().getUser().getUsername(), getMainBean().getModel().getUser().getPassword());
    if (user != null) {
        getMainBean().getModel().setUser(user);
        logger.info("User '"+getMainBean().getModel().getUser().getUsername()+"' logged in");
        getMainBean().getModel().setSelectedTab(0);
    } else {
        FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,"Login failed", "Username and/or password wrong!"));
        logger.warn("User '"+getMainBean().getModel().getUser().getUsername()+"' login failed");
    }
    return null;
}

UserDao

package myPackage.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import myPackage.entity.User;

@Repository
public class UserDao {

@PersistenceContext
private EntityManager entityManager;

@Transactional
public void save(User user) {
    if (user.getId() == null) {
        entityManager.persist(user);    
    } else {
        entityManager.merge(user);
    }
}

@SuppressWarnings("unchecked")
public List<User> list() {
    return entityManager.createQuery("select u from User u")
            .getResultList();
}

public User getUserByUsername(String username) {
    try {
        Query q = entityManager.createQuery("select u from User u where u.username = :username");
        q.setParameter("username", username);
        User u = (User) q.getSingleResult();
        return u;
    } catch (Exception e) {
        return null;
    }
}

public User getUserByUsernameAndPassword(String username, String password) {
    try {
        Query q = entityManager.createQuery("select u from User u where u.username = :username and u.password = :password");
        q.setParameter("username", username);
        q.setParameter("password", password);
        User u = (User) q.getSingleResult();
        return u;
    } catch (Exception e) {
        return null;
    }
}

@Transactional
public User getUserById(Long id) {
    return entityManager.find(User.class, id);
}

@Transactional
public void delete(User user) {
    entityManager.remove(user);
}

public void deleteById(Long id) {
    delete(getUserById(id));
}

}

그리고 지금은 예외 ...

Caused by: java.lang.NullPointerException
    at myPackage.bean.UserBean.doLogin(UserBean.java:47)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)

47 행 :

    User user = userDao.getUserByUsernameAndPassword(getMainBean().getModel().getUser().getUsername(), getMainBean().getModel().getUser().getPassword());

디버깅은 getMainBean ()이 null을 반환한다는 것을 보여줍니다.

나는 내 개념을 개선 할 것을 제안합니다!

해결법

  1. ==============================

    1.JSF 백업 빈 (MainBean 및 UserBean)은 JSF 또는 Spring 중 하나에서 관리해야하지만 둘 다 관리해서는 안됩니다.

    JSF 백업 빈 (MainBean 및 UserBean)은 JSF 또는 Spring 중 하나에서 관리해야하지만 둘 다 관리해서는 안됩니다.

    콩이 JSF에 의해 관리된다면 :

    콩이 Spring에 의해 관리된다면 :

    두 경우 모두 faces-context.xml에서 Spring-JSF bridge를 설정해야한다.

    <application>
        <el-resolver>
            org.springframework.web.jsf.el.SpringBeanFacesELResolver
        </el-resolver>
    </application>
    
  2. from https://stackoverflow.com/questions/12243873/managedproperty-in-a-spring-managed-bean-is-null by cc-by-sa and MIT license