Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/343.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java @自动连线bean在静态方法中为null_Java_Spring_Spring Mvc_Static_Autowired - Fatal编程技术网

Java @自动连线bean在静态方法中为null

Java @自动连线bean在静态方法中为null,java,spring,spring-mvc,static,autowired,Java,Spring,Spring Mvc,Static,Autowired,我有两个类名:Bean类和Util类。在Util类中,我想从Bean类调用该方法。但问题是当我在Util类中@Autowired Bean类时。由于Util类中的静态方法,存在空指针异常。这是我的密码 public class Util{ @Autowired private static BaseServiceCommonPropertiesBean baseServiceCommonPropertiesBean; private static String PASSPHRASE = ba

我有两个类名:Bean类和Util类。在Util类中,我想从Bean类调用该方法。但问题是当我在Util类中@Autowired Bean类时。由于Util类中的静态方法,存在空指针异常。这是我的密码

public class Util{

@Autowired
private static BaseServiceCommonPropertiesBean baseServiceCommonPropertiesBean;

private static String PASSPHRASE = baseServiceCommonPropertiesBean.getBassURL();
System.out.print(PASSPHRASE);

}
下面是BaseServiceCommonPropertiesBean类的示例

public class BaseServiceCommonPropertiesBean {

@Value("#{baseServiceapplicationProperties['mobi.sc.travellers.amr.email.base.url']}")
    private String baseUrl;

public String getBaseUrl(){
        return baseUrl;
    }

}


每当系统读取baseServiceCommonPropertiesBean.getPassPhrase()方法时。它出去了,停止工作了。在@Postconstruct注释无效之前,我尝试过它。谢谢。

您不能@Autowired static fields,或者从BaseServiceCommonPropertiesBean中删除static,或者将您的Util重写为如下内容:

@Component
public class Util{

private static BaseServiceCommonPropertiesBean baseServiceCommonPropertiesBean;

@Autowired
    public void setBaseServiceCommonPropertiesBean(BaseServiceCommonPropertiesBean baseServiceCommonPropertiesBean){
        Util.baseServiceCommonPropertiesBean = baseServiceCommonPropertiesBean;
    }

private static String PASSPHRASE = baseServiceCommonPropertiesBean.getBassURL();
System.out.print(PASSPHRASE);

}

是,您不能在静态字段上使用@Autowired。“在@Postconstruct注释不起作用之前”是什么意思?(它的行为肯定与它的文档相符)-你能编辑这个问题来向我们展示你的尝试吗?更重要的是,为什么要静态地设置密码短语?例如,为什么实例上的
getPassphrase()
方法不够?spring的好处之一是不必使用静态字段。不能使用getPassphrase()或BaseServiceCommonPropertiesBean的所有get方法。对于PostConstruct,在它不起作用之前,我使用了下面的代码。仍然作为空指针异常出现。谢谢@组件公共类Util{private static baseServiceCommonProperties bean baseServiceCommonProperties bean;@Autowired private baseServiceCommonProperties bean;@PostConstruct private void initStaticBean(){baseServiceCommonProperties bean=this.bean;}}`不要使用
静态
。可能重复感谢您的帮助。我试过你说的方式。但是仍然有错误并且没有任何结果@3_eyed_raven。如果在spring之前没有扫描Util的创建和自动连接,那么它应该如何工作呢?据我所知,你不能简单地把@Autowired称为day@KaungKhantZaw-我自己还没有尝试过,答案是一般性的指导,尝试向Util类添加@Component。另外,为什么不使用非静态Util呢?