【问题标题】:why is the injected bean value is null为什么注入的bean值为null
【发布时间】:2014-10-30 08:36:02
【问题描述】:

我有一个自定义标签。当我注入spring消息资源并想要访问属性文件时,注入的bean始终为null。 我做错了什么,

 @Component
public class GridColumnsCutomTagHander extends TagSupport {

/**
 * 
 */
private static final long serialVersionUID = 1L;

@Inject
private MessageSource messageSource;

private String propertyFileName;

/**
 * @return the propertyFileName
 */
public String getPropertyFileName() {
    return this.propertyFileName;
}

/**
 * @param propertyFileName
 *            the propertyFileName to set
 */
public void setPropertyFileName(String propertyFileName) {
    this.propertyFileName = propertyFileName;
}

@Override
public int doStartTag() throws JspException {

    try {
        JspWriter out = pageContext.getOut();
        String gridColumnValues = messageSource.getMessage(propertyFileName,
                null, EWMSUser.getCurrentLanguageLocale());
        out.println(gridColumnValues );
    } catch (IOException e) {
        e.printStackTrace();
    }

    return (SKIP_BODY);
}

请帮助我找出问题所在

【问题讨论】:

  • 什么是消息源?类或接口。你能显示 Spring 的 XML 配置吗

标签: spring-mvc inject


【解决方案1】:

根据我的经验,MessageSource 可以注入成功如果当前类有 servletContext 环境。所以你需要在你的 contronller 层,然后将其作为构造参数传递给您当前的标记类。

为了做到这一点,我认为你不应该使用@Componment 来初始化 GridColumnsCutomTagHander 类,你需要在你的代码中手动创建它。下面是我的解决方案:

  • GridColumnsCutomTagHander 类的代码
public class GridColumnsCutomTagHander extends TagSupport {


private static final long serialVersionUID = 1L;


private MessageSource messageSource;

public GridColumnsCutomTagHander(){
}

public GridColumnsCutomTagHander(MessageSource messageSource){
   this.messageSource=messageSource;
}

private String propertyFileName;

/**
 * @return the propertyFileName
 */
public String getPropertyFileName() {
    return this.propertyFileName;
}

/**
 * @param propertyFileName
 *            the propertyFileName to set
 */
public void setPropertyFileName(String propertyFileName) {
    this.propertyFileName = propertyFileName;
}

@Override
public int doStartTag() throws JspException {

    try {
        JspWriter out = pageContext.getOut();
        String gridColumnValues = messageSource.getMessage(propertyFileName,
                null, EWMSUser.getCurrentLanguageLocale());
        out.println(gridColumnValues );
    } catch (IOException e) {
        e.printStackTrace();
    }

    return (SKIP_BODY);
}
  • 在控制器层类中使用它:
@Controller   
public TestController{

 @Inject
 private MessageSource messageSource;

@RequestMapping("test")
 public void test(){
   new GridColumnsCutomTagHander(messageSource);//now the messageSource is not null
 }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-09
    • 1970-01-01
    • 1970-01-01
    • 2013-06-20
    • 2011-12-04
    • 1970-01-01
    • 2017-12-12
    相关资源
    最近更新 更多