I know it is not a best design but just a thought from a Spring newbie.
Now we can easily autowire any service method to each other conveniently in Spring framework. But What is the disadvantage to create a static factory method of the service class and call it everywhere?
It’s pretty common like this:
@Autowired
CustomerService customerService;
....
AccountDetail ad = customerService.getAccountDetail(accountId, type);
But this should work too:
// If we make getAccountDetail(String, String) static:
AccountDetail ad = CustomerService.getAccountDetail(accountId, type);
So why there is a design like autowire? It looks fancy and really cool, but the work behind this is still create one service bean instance on another service object.
Seriously while Spring is all over the market so many posts and articles are talking about pros & renovations. But is it guaranteeing better performance(like using autowire instead of static)?
There are numerous reasons:
you can’t replace
CustomerServicewith a mock easily during tests (tools like PowerMock aside)staticmethods do not participate in standard, proxy-based AOP (no transactions, security, custom aspects)you can no longer use fancy injection techniques, like injecting HTTP request (request scoped) into singleton scoped services (poor design anyway, but…)
But to be complete, there are also advantages:
staticmethod is actually closer to your intent, Spring beans are very rarely stateful, thus they don’t really need an instance to workstaticcall might be faster (this is irrelevant in 99% of the programs)