autowired 静态方法使用_@Autowired和静态方法

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:

Using constructor @Autowired

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

}

}

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

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值