用于在Spring 3中访问服务的Util类

时间:2010-12-14 17:11:42

标签: spring static-methods utility-method

在Spring 3中,无法在静态字段或方法中设置@Autowired,因此我想声明一个实用程序类,例如:

public class SchoolYearServiceUtil {
    private static SchoolYearService schoolYearService;

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

避免在我需要的地方注入schoolYearService(jsp,命令类...)。在这种情况下,我不需要由SchoolYearServiceUtil实现的接口。

我不想通过代码初始化对象,而是获得与Spring相同的实例。

哪个是将getSchoolYear实现为静态方法的最佳选择?

感谢。

这在概念上是错误的吗?:

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

我必须确保一旦构造​​函数和构造函数被调用,只有Spring调用,这就是我将构造函数声明为私有的原因。

1 个答案:

答案 0 :(得分:1)

我完全支持skaffman的评论。 DI不需要static个字段。您只需定义范围单例的bean(默认)。

有一种方法可以静态获取bean,但是你应该知道它不能在常规情况下使用。 (有一些有效的申请)。这是使用WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext)

您注意到需要传递ServletContext参数。

相关问题