KaungKhant Zaw
KaungKhant Zaw

Reputation: 37

@Autowired bean is coming as null at static method

i have two class name with Bean class and Util class. At Util class i want to call the method from Bean Class. But the thing is when i @Autowired the Bean class at Util class. There is null pointer exception because of static method at Util class. Here is my code.

public class Util{

@Autowired
private static BaseServiceCommonPropertiesBean baseServiceCommonPropertiesBean;

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

}

Here is for BaseServiceCommonPropertiesBean class

public class BaseServiceCommonPropertiesBean {

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

public String getBaseUrl(){
        return baseUrl;
    }

}

Whenever the system read the baseServiceCommonPropertiesBean.getPassPhrase() method. It goes out and stop working . I tried @Postconstruct annotation before it does not work. Thanks.

Upvotes: 0

Views: 4201

Answers (1)

3_eyed_raven
3_eyed_raven

Reputation: 43

You cannot @Autowired static fields, either remove static from BaseServiceCommonPropertiesBean or rewrite your Util to be something like below:

@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);

}

Upvotes: 1

Related Questions