Posts

Showing posts with the label dependecy injection

Dependency injection pitfalls in Spring

There are three injection variants in Spring framework: Setter-based injection Constructor-based injection Field-based injection Each of those mechanisms has advantages and disadvantages and there is not only one right approach. For example field injection: @Autowired private FooBean fooBean; It's generally not the best idea to use it in the production code, mostly because it makes our beans impossible to test without starting Spring context or using reflection hacks. On the other hand it requires almost no additional code and could be used in integration tests - which definitely won't be instantiated independently. And in my opinion this is the only case for field-based injections. Now let's focus on two major variants. In  Spring documentation  we can read that ...it is a good rule of thumb to use constructor arguments for mandatory dependencies and setters for optional dependencies. Also in documentation referring Spring up to 3.1 we could find a sentenc...

Injecting Spring beans into non-managed objects

Advantages coming from dependency injection can be addicting. It's a lot easier to configure application structure using injections than doing all resolutions manually. It's hard to resign from it when we have some non-managed classes that are instantiated outside of the container - for example being part of other frameworks like Vaadin UI components or JPA entities. The latter are especially important when we're using Domain Driven Design . During DDD training ran by Slawek Sobotka  we were talking about options to remove "bad coupling" from aggregate factories. I'm sure you'll admit, that it's better to have generic mechanism able to "energize" objects by dependencies defined by e.g. @Inject annotation than inject all necessary dependencies into particular factory and then pass them into object by constructor, builder or simple setters. Spring framework brings us two different solutions to achieve such requirement. I'll now describe ...