Reputation: 27445
I have the following class that takes processing events:
public abstract class EventExecutor {
public static final EventExecutor ON_BALANCE_CHANGE_EXECUTOR = new EventExecutor() {
private BalanceDao balanceDao;
@Override
public void executeEvent() {
BigDecimal balance;
//getting the balance
balanceDao.add(balance);
}
//GET, SET, others
};
public abstract void executeEvent();
}
The thing is processing some events means to save some data into a persistent store. Since I use Spring 4 I need to perform a corresponding dependency injection in order to perform db
-operation.
Curretly, I intent to allow client to perform event handlings via invoking methods on static final fields in order to increase code readability.
So, there is a possibility to do that via ContextLoader.getCurrentWebApplicationContext().getBean(String beanName)
but it introduces spring dependencies which is not a desirable solution.
Maybe there is some spring feature allowing us to do that? Couldn't you suggest anything about that?
Upvotes: 1
Views: 919
Reputation: 582
Since you create object by hand you cannot inject beans directly in anonymous class. The possible solution is to create static inner class for ON_BALANCE_CHANGE_EXECUTOR and define bean of this type in your config.
public abstract class EventExecutor {
public static class OnBalanceChangeExecutor extends EventExecutor {
private BalanceDao balanceDao;
@Override
public void executeEvent() {
BigDecimal balance;
//getting the balance
balanceDao.add(balance);
}
//GET, SET, others
}}
After that you can create bean in your context config:
<bean id="onBalanceChangeExecutor" class = "your.package.EventExecutor$OnBalanceChangeExecutor">
<property name="balanceDao" ref="balanceDao"/>
</bean>
Upvotes: 2