简体   繁体   English

Spring不能静态引用非静态方法吗?

[英]Spring can't make static reference to non-static method?

This is my PageController code. 这是我的PageController代码。

@RequestMapping(value = { "/show/category/{id}/products" })
public ModelAndView showCategoryProducts(@PathVariable("id") int id) {

    // Category DAO  //Getting Error Here
    Category category = null;//Please  Explain this line also.
    category = CategoryDAO.get(id);// Getting Error in this line

    ModelAndView mv = new ModelAndView("page");
    mv.addObject("title", "All Products");
    // Passing list of categories
    mv.addObject("categories", categoryDAO.list());
    mv.addObject("userClickCategoryProducts", true);
    return mv;
}

Code in CategoreDAO Class CategoreDAO类中的代码

public interface CategoryDAO {
    List<Category> list();
    Category get(int id);
}

Another class Which Implements CategoryDAO class 实现CategoryDAO的另一个类

Repository("CategoryDAO")
public class CategoryDAOImpl implements CategoryDAO {
    private static List<Category> categories = new ArrayList<>();

    static {@Override
    public Category get(int id) {

        for(Category category:categories) {
            if(category.getId()==id)
                return category;
        }

    return null;
}

I am getting an error that static reference can't make non-static method. 我收到一个错误,指出静态引用不能成为非静态方法。

Please take a look in the first code snippet. 请查看第一个代码段。 You'll understand the problem 您会明白问题所在

Yeah, Absolutely. 是的,绝对如此。

Static and non static object work differently. 静态对象和非静态对象的工作方式不同。 With non static method, you must instantiate before using. 对于非静态方法,必须在使用之前实例化。 So that's why it's not valid to use non static method in static method. 这就是为什么在静态方法中使用非静态方法无效的原因。

One more thing, the static block will be invoked before constructor. 还有一件事,将在构造函数之前调用静态块。 So please double check your business logic. 因此,请仔细检查您的业务逻辑。 I don't understand so much why to override other function in static block. 我不太明白为什么要覆盖静态块中的其他功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM