0

I am building a webapp which needs to access application.properties through Environment object.Have a look at my code below.

@Configuration
@ComponentScan(basePackages = "com.asn.myutilities")
@PropertySource(value = { "classpath:application.properties" })
public class AppConfig {

    /*
     * PropertySourcesPlaceHolderConfigurer Bean only required for @Value("{}")
     * annotations. Remove this bean if you are not using @Value annotations for
     * injecting properties.
     */
    @Bean
    public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
        return new PropertySourcesPlaceholderConfigurer();
    }
}

public interface AuthService {
    void readValues();
}


@Service("authService")
public class AuthServiceImpl implements AuthService {

    @Autowired
    private Environment environment;

    public void readValues() {
        System.out.println("Getting property via Spring Environment :"
                + environment.getProperty("userProfileServiceUserName"));


    }
}


@Component
public class DelegatorUtil {


    @Autowired
    static AuthService authService; // coming as null

    public static final String serviceCall(HttpServletRequest request,
            String baseUri, RequestMethod requestMethod)
            throws Exception {

        String responseBody = "";

        String[] parts = baseUri.split("/");
        String microServiceEndPoint = parts[3];
        authService.readValues(); // NPE
}
}

Can any one answer my question why NPE coming for the auto wired object in DelegatorUtil class? I tried many ways but not able to figure out how to solve this issue.

Many Thanks

isudarsan
  • 437
  • 1
  • 6
  • 14

2 Answers2

0

You are using '@Autowire' on a static field. Spring doesn't support this. To solve your problem you need to remove 'static' from the field and method declaration

Check this question this

JohnnyAW
  • 2,866
  • 1
  • 16
  • 27
  • Yes my bad, we should not use @Autowire in static context, resolved using PostConstruct. – isudarsan Feb 03 '18 at 04:43
  • Please accept one answer(any one is fine), if it this solves your problem so that it does not show up in unanswered tab of stackoverflow. – best wishes Feb 03 '18 at 10:51
0

change static AuthService authService;

to AuthService authService;

more about it here Can you use @Autowired with static fields?

best wishes
  • 5,789
  • 1
  • 34
  • 59