开发者

Util class for accesing a Service in Spring 3

开发者 https://www.devze.com 2023-01-31 02:39 出处:网络
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:

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() {
    r开发者_JAVA技巧eturn 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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消