小编典典

@Autowired和静态方法

spring

我有@Autowired必须从静态方法中使用的服务。我知道这是错误的,但是我无法更改当前的设计,因为这需要大量的工作,因此我需要一些简单的技巧。我不能更改randomMethod()为非静态,并且需要使用此自动装配的bean。有什么线索怎么做?

@Service
public class Foo {
    public int doStuff() {
        return 1;
    }
}

public class Boo {
    @Autowired
    Foo foo;

    public static void randomMethod() {
         foo.doStuff();
    }
}

阅读 745

收藏
2020-04-12

共1个答案

小编典典

使用构造函数@Autowired
这种方法将构造需要一些bean作为构造函数参数的bean。在构造函数代码中,您可以将静态字段的值设置为构造函数执行的参数。

@Component
public class Boo {

    private static Foo foo;

    @Autowired
    public Boo(Foo foo) {
        Boo.foo = foo;
    }

    public static void randomMethod() {
         foo.doStuff();
    }
}

使用@PostConstruct将值移交给静态字段
这里的想法是在通过spring配置bean之后将bean移交给静态字段。

@Component
public class Boo {

    private static Foo foo;
    @Autowired
    private Foo tFoo;

    @PostConstruct
    public void init() {
        Boo.foo = tFoo;
    }

    public static void randomMethod() {
         foo.doStuff();
    }
}
2020-04-12