java - spring3 - 应用程序上下文 - bean属性名称和引用 - 空指针异常

标签 java spring

全部 - 在 Spring 3.0 中,在 applicationContext.xml 中 ....我们应该让 bean 属性名称和引用值相同吗?如果我给出不同的值,它将返回 null 对象。但在给予相同的值(value)时,它是有效的。对于我的项目,我应该为它们赋予不同的值。请帮忙。再见,HS

这有效:(相同的值)

<bean id="MNCWIRAdminBaseAction" class="com.megasoft.wiradmin.web.action.WIRAdminBaseAction"> 
<property name="cacheDelegate"> 
<ref bean="cacheDelegate" /> 
</property> 
</bean>

这不起作用:(不同的值)

<bean id="MNCWIRAdminBaseAction" class="com.megasoft.wiradmin.web.action.WIRAdminBaseAction"> 
<property name="cacheDelegate"> 
<ref bean="MNCCacheDelegate" /> 
</property> 
</bean> 

再见,HS

我的完整代码在这里:

WIRAdminBaseAction.java ---> my base action 
AuthenticateAction.java ---> my java file that calls the bean here 
applicationContext.xml --> system's applicationcontext file
applicationContext_MNC.xml ---> my applicationContext for a specific company ... this is getting loaded by my java file, which gets invoked by the web.xml file. 
CacheDelegate.java
StatusDBDAO.java
PreXMLWebApplicationContext.java ----> loads my applicationContext file for the specific company.

****** applicationContext.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:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
    http://www.springframework.org/schema/aop 
    http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">
    <bean name="exceptionHandler" class="com.megasoft.wir.eStatement.web.interceptor.WIRExceptionHandlerInterceptor"/>
    <bean name="security" class="com.megasoft.wir.eStatement.web.interceptor.SecurityInterceptor"/>
    <bean name="permission" class="com.megasoft.wir.eStatement.web.interceptor.PermissionInterceptor"/>

  <!-- AutoProxies -->
  <bean name="loggingAutoProxy" class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
    <property name="interceptorNames">
        <list>
          <value>base</value>
          <value>exceptionHandler</value>
          <value>security</value>
          <value>permission</value>
        </list>
    </property>
   </bean>
</beans>



****** applicationContext_MNC.xml ******

<?xml version="1.0" encoding="UTF-8"?> 
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" 
"http://www.springframework.org/dtd/spring-beans.dtd"> 

<beans> 

<bean id="MNCWIRAdminBaseAction" class="com.megasoft.wiradmin.web.action.WIRAdminBaseAction"> 
<property name="cacheDelegate"> 
<ref bean="MNCCacheDelegate" /> 
</property> 
</bean> 

<bean id="MNCCacheDelegate" class="com.megasoft.wiradmin.delegate.CacheDelegate" > 
<property name="statusDBDAO"><ref bean="MNCStatusDBDAO" /></property> 
</bean> 

<bean id="MNCStatusDBDAO" class="com.megasoft.wiradmin.dao.StatusDBDAO"> 
<property name="dataSource"> 
<ref bean="MNCAdminDataSource" /> 
</property> 
</bean> 

<!-- database configuration from property file --> 
<bean id="MNCAdminDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" 
destroy-method="close" lazy-init="default" autowire="default" dependency-check="default"> 
<property name="driverClass" value="${jdbc.driver}" ></property> 
<property name="jdbcUrl" value="${admin.jdbc.url}" ></property> 
<property name="user" value="${admin.jdbc.user}" ></property> 
<property name="password" value="${admin.jdbc.password}" ></property> 
<property name="initialPoolSize" value="3" ></property> 
<property name="minPoolSize" value="3" ></property> 
<property name="maxPoolSize" value="25" ></property> 
<property name="acquireIncrement" value="1" ></property> 
<property name="acquireRetryDelay" value="1000" ></property> 
<property name="debugUnreturnedConnectionStackTraces" value="true" ></property> 
<property name="maxIdleTime" value="300" ></property> 
<property name="unreturnedConnectionTimeout" value="300000" ></property> 
<property name="preferredTestQuery" value="SELECT COUNT(*) FROM LOCALE_CODE" ></property> 
<property name="checkoutTimeout" value="300000" ></property> 
<property name="idleConnectionTestPeriod" value="600000" ></property> 
</bean> 

<!-- this bean is set to map the constants which needs to be configured as per 
the environment to the java constants file --> 
<bean id="envConstantsConfigbean" class="com.megasoft.wiradmin.util.constants.Environm entConstantsSetter"> 
<property name="loginUrl" value="${login.url}"/> 
<property name="logoutIR" value="${logout.from.image.retrieval}"/> 
<property name="adminModuleUrl" value="${admin.url}"/> 
<property name="adminUrlSym" value="${admin.url.sym}"/> 
<property name="envProperty" value="${env.property}"/> 
</bean> 

</beans> 

****** AuthenticateAction.java ******

package com.megasoft.wiradmin.web.action; 

import java.net.UnknownHostException; 
import java.sql.SQLException; 

import org.bouncycastle.crypto.CryptoException; 
import org.springframework.context.ApplicationContext; 
import org.springframework.dao.DataAccessException; 
import org.springframework.web.context.support.WebApplica tionContextUtils; 

import com.megasoft.wiradmin.delegate.ICacheDelegate; 

public class AuthenticateAction extends WIRAdminBaseAction { 

private static final long serialVersionUID = 1L; 

public String authenticate() throws UnknownHostException, CryptoException, 
DataAccessException, SQLException{ 

/** This way of calling works...... This is not encouraged, as we should not use applicationContext always **/ 
ApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContex t(getServletRequest().getSession().getServletConte xt()); 
ICacheDelegate cacheAction = (ICacheDelegate) applicationContext.getBean("MNCCacheDelegate"); 

/** The below way of calling does NOT work .... returns null value.... Please help... 
* I assume that, since I have extended the WIRAdminBaseAction, i should be able to call the getCacheDelegate directly 
* and it should return my cacheDelegate object ... 
* Again, Please note.....if I change my applicationContext_MNC.xml as below, the below way of calling works fine... 
* but, i don't want to change my applicationContext_MNC.xml as below, due to some necessity. 
*
<bean id="MNCWIRAdminBaseAction" class="com.megasoft.wiradmin.web.action.WIRAdminBaseAction"> 
<property name="cacheDelegate"> 
<ref bean="cacheDelegate" /> 
</property> 
</bean> 
*
<bean id="cacheDelegate" class="com.megasoft.wiradmin.delegate.CacheDelegate" > 
<property name="statusDBDAO"><ref bean="MNCStatusDBDAO" /></property> 
</bean> 
*
... is it that the name and bean should have the same value.... ??? No Need to be.....Am i right ? Please advise. 
* 
* **/ 

getCacheDelegate().getActorAction(1); // this way of calling doesn't work and returns null value. please help. 

return "success"; 
} 
} 


****** WIRAdminBaseAction.java ******

package com.megasoft.wiradmin.web.action; 


import java.util.Map; 

import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse; 

import org.apache.struts2.interceptor.ParameterAware; 
import org.apache.struts2.interceptor.SessionAware; 

import com.opensymphony.xwork2.ActionSupport; 
import com.opensymphony.xwork2.Preparable; 
import com.opensymphony.xwork2.config.entities.Parameteri zable; 
import com.megasoft.wiradmin.delegate.ICacheDelegate; 

public class WIRAdminBaseAction extends ActionSupport implements Preparable, ParameterAware, Parameterizable, SessionAware,RequestAware { 

private HttpServletRequest request; 
private static final long serialVersionUID = 1L; 
private HttpServletResponse response; 

private ICacheDelegate cacheDelegate; 

private Map session; 

private Map<String, String> params; 

private Map parameters; 

public void prepare() throws Exception { 
} 

public String execute() throws Exception { 
return SUCCESS; 
} 

public void setServletRequest(HttpServletRequest request) { 

this.request = request; 
} 

public HttpServletRequest getServletRequest() { 
return this.request; 
} 

public void setServletResponse(HttpServletResponse response) { 
this.response = response; 
} 

public HttpServletResponse getServletResponse() { 
return this.response; 
} 

public ICacheDelegate getCacheDelegate() { 
return cacheDelegate; 
} 

public void setCacheDelegate(ICacheDelegate cacheDelegate) { 
this.cacheDelegate = cacheDelegate; 
} 

public void addParam(final String key, final String value) { 
this.params.put(key, value); 
} 

public Map getParams() { 
return params; 
} 

public void setParams(final Map<String, String> params) { 
this.params = params; 
} 

public Map getSession() { 
return this.session; 
} 

public void setSession(final Map session) { 
this.session = session; 
} 

public void setParameters(final Map param) { 
this.parameters = param; 
} 

} 

PreXMLWebApplicationContext.java **

package com.megasoft.wiradmin.util;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.context.support.XmlWebApplicationContext;

public class PreXMLWebApplicationContext extends XmlWebApplicationContext {

      /**
     * This initializes the Logger.
     */
    private static Log logger = LogFactory.getLog(PreXMLWebApplicationContext.class);

    protected String[] getDefaultConfigLocations() {

        String environment = System.getProperty("envProperty");
        String webirConfig = System.getProperty("webirConfig");
        String fi = System.getProperty("FI");
        String preHostConfiguration =null;

        logger.info("The environment is "+environment);
        logger.info("The webirConfig is "+webirConfig);
        logger.info("The fi is "+fi);

        if(environment != null && webirConfig != null && fi != null) {
            preHostConfiguration = DEFAULT_CONFIG_LOCATION_PREFIX +  
                     "classes/applicationContext" + "_" + fi.toUpperCase() + 
                                               DEFAULT_CONFIG_LOCATION_SUFFIX;
        }
        return new String[]{DEFAULT_CONFIG_LOCATION, preHostConfiguration};
    }

    /**
     * This is close API.
     * 
     * @see org.springframework.context.support.AbstractApplicationContext
     *                                                                  #close()
     */
    public void close() {
        this.doClose(); 
        logger.info("Login-->into the closed");
    }
}

最佳答案

<property name="userDelegate" ref="userDelegate" />

name是您类(class)中的字段名称。当名字是userDelegate时,这意味着WIRAdminBaseAction有一个名为 userDelegate 的字段(可能还有一个二传手 setUserDelegate() )

ref是您想要将此字段设置为的 bean 名称。在您的示例中,您应该有另一个 bean,名为 userDelegatebmoUserDelegate应设置为 userDelegateWIRAdminBaseAction .

因此,如果您想使用第二种配置:

你只需要创建一个id为bmoUserDelegate的bean :

<bean id="bmoUserDelegate" class="mypackage.BmoUserDelegateClass"/>

关于java - spring3 - 应用程序上下文 - bean属性名称和引用 - 空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19709852/

相关文章:

java - 如何使用属性名称识别 setter 方法?

java - 通过 Spring Controller 映射图像文件

json - 如何在 Spring 全局异常处理程序中处理 JSON 方法中的不同异常?

java - 在 Spring PropertyPlaceholderConfigurer 中配置局部变量

java - 将 @OneToMany 与 @OneToOne 一起使用是否正确?

java - 无法在 Apache Kafka 中启动 Zookeeper 服务器

java - php 中的 SHA1 加密和 SHA1 到 Hex

java - 哪个 JAR 包含 org.springframework.orm.hibernate.HibernateTransactionManager?

java - 带有对象的ArrayList,排序并找到最大的对象(按面积排列的矩形)

java - Spring REST 如何以不同方式验证请求主体?