簡體   English   中英

如何在Spring中從另一個類訪問變量

[英]How to access a variable from another class in Spring

我試圖通過Spring中的自動裝配從另一個類訪問變量,但是我得到一個空指針。 我唯一的方法是將其重新實例化為靜態。 有沒有一種方法可以在非靜態上下文中訪問它(變量),例如自動裝配?

通過靜態:

@Component
@Scope(proxyMode = ScopedProxyMode.TARGET_CLASS, value = "prototype")
public class ClassWhereVariableIsNeeded {

    public static void setViews(Views aViews) {
        views = aViews;
    }

    private static Views views;
    .
    .
    .

    private void method() {
        views.thisVariable.....
    }

我想要這樣:

@Component
@Scope(proxyMode = ScopedProxyMode.TARGET_CLASS, value = "prototype")
public class ClassWhereVariableIsNeeded {

    @Autowired
    Views views;
    .
    .
    .

    private void method() {
        views.thisVariable.....
    }

變量所在的位置:

@Component
@Scope(proxyMode = ScopedProxyMode.TARGET_CLASS, value = "prototype")
public class Views extends ClassWhereVariableIsNeeded {


    ThisVariable thisVariable;
    .
    .
    .

要訪問任何變量和/或方法,必須將此變量/方法訪問修飾符設置為高於private。 private修飾符將訪問限制在定義(或內部)類之內,而沒有其他地方。 您可以為其他類提供public / default / package(訪問)方法,以使用/訪問您的私有變量

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM