@Autowired和静态方法 [英] @Autowired and static method

查看:1609
本文介绍了@Autowired和静态方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have @Autowired service which has to be used from within a static method. I know this is wrong but I cannot change the current design as it would require a lot of work, so I need some simple hack for that. I can't change randomMethod() to be non-static and I need to use this autowired bean. Any clues how to do that?

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

public class Boo {
    @Autowired
    Foo foo;

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


推荐答案

你可以通过以下解决方案之一来做到这一点:

You can do this by following one of the solutions:

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

This approach will construct the bean requiring some beans as constructor parameters. Within the constructor code you set the static field with the value got as parameter for constructor execution. Sample:

@Component
public class Boo {

    private static Foo foo;

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

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



使用@PostConstruct将值移交给静态字段



这里的想法是在bean由spring配置之后将bean移交给静态字段。

Using @PostConstruct to hand value over to static field

The idea here is to hand over a bean to a static field after bean is configured by spring.

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

这篇关于@Autowired和静态方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆