java inner enum_how to inject a dependency in a java enum?

可以将文章内容翻译成中文,广告屏蔽插件会导致该功能失效:

问题:

I am trying to inject a bean into an enum but i keep getting null pointer exception when call to someMethod is made.

The answer mentioned in this Inject bean into enum worked for me. I want to know why my code didn't work

@Component

public class DataProvider {

public int method1() {

//somecode

}

}

public enum Genres {

DRAMA(1,”Drama”);

ADVENTURE(2,”Adventure”);

HORROR(3,”Horror”);

private int id;

private String name;

@Inject DataProvider dataprovider;

public int someMethod() {

return dataprovider.method1();

}

}

回答1:

What the answer you linked does is loop the enum values and use a setter to inject the DataProvider dependency

public void postConstruct() {

for (ReportType rt : EnumSet.allOf(ReportType.class)) {

rt.setDataPrepareService(dataPrepareService);

}

}

It works because the ReportTypeServiceInjector class is an inner, static class, and so it can be seen and instantiated by Spring.

It's a crazy design anyway. Avoid it.

Ultimately, keep the enum simple and extract the DataProvider usage.

Your original code didn't work because Spring cannot @Autowire/@Inject dependencies in enums.

回答2:

Generally, it is not a good practice to have dependency injection in enums as they are designed to be constants/static (Reference)

But, I agree with you, many times, we need to associate some real time behavior to be encapsulated along with Enum values.

I would suggest, create a new class and encapsulate Enum within that.

class GenresService{

// 1st option: Declare Genres enum reference at class level and

// initialize using class constructor/injection.

// Genres g;

@Inject DataProvider dataprovider;

//2nd option: pass Genres value to method at real time.

public int someMethod(Genres g) {

return dataprovider.method1();

}

}

回答3:

To have any injection to work you would need to have your enum also managed. You could try to inject your enum but how and what would you inject? It presents constant values and in addition it has private no args constructor.

So the way you might have it working would be some JNDI lookup - that initializes dataProvider - inside your someMethod() or using some static context accessor.

And: for for Spring it is not @Inject but @Resource or @Autowired

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值