Question

In Spring 3 it is not possible to set @Autowired in either static fields or methods, so since I want to declare an utility class such as:

public class SchoolYearServiceUtil {
    private static SchoolYearService schoolYearService;

    public static SchoolYear getSchoolYear(Long id) {
        return schoolYearService.get(id);
    }
}

to avoid having to inject the schoolYearService everywhere (jsp, command class...) in which I need it. In this case, I don't need an interface to be implemented by SchoolYearServiceUtil.

I don't want to have to initialize the object through code but getting the same instance as the Spring's one.

Which would be the best option to implement the getSchoolYear as a static method?

Thanks.

Would this be conceptually wrong?:

@Component
public class SchoolYearServiceUtil {

private static SchoolYearService schoolYearService;

@Autowired(required = true)
private SchoolYearServiceUtil(@Qualifier("schoolYearServiceImpl") SchoolYearService schoolYearService) {
    SchoolYearServiceUtil.schoolYearService = schoolYearService;
}

public static SchoolYearService getSchoolYearService() {
    return schoolYearService;
}

public static SchoolYear getSchoolYear(Long id) {

    return getSchoolYearService().get(id);
}
}

I would have to make sure that only Spring calls once the constructor and the constructor is called nowhere else, that's why I declared the constructor as private.

Was it helpful?

Solution

I fully support skaffman's comment. You don't need static fields with DI. You just define a bean of scope singleton (default).

There is a way to obtain a bean statically, but you should be aware that it is not to be used in regular situations. (there are some valid applications). It is to use the WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext)

You notice that you need to pass a ServletContext argument.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top