Explain Codes LogoExplain Codes Logo

Understanding Spring @Autowired usage

java
spring
autowired
bean-injection
Anton ShumikhinbyAnton ShumikhinΒ·Dec 7, 2024
⚑TLDR

To spring you into action quickly, just remember @Autowired in Spring will remove the sweat of manual dependency linking. Pin the @Autowired on your class member and Spring has your back, reaches into its hat (the context), and pulls out the matching bean.

Wham-bam-example:

@Component public class Vehicle { // Engine could use oil... or maybe some coffee? πŸ‘€ @Autowired private Engine engine; // Full steam ahead! Spring adds Engine here } @Component public class Engine {}

No need to roll up your sleeves, Spring does the digging. Every @Component annotation is a flare seen by Spring, marking the place where it should draft into the service of potential injection points.

A leap into various implementations

Several species of the same bean? Use the magic wand @Qualifier to pick the chosen one.

Working example:

@Component public class Vehicle { // ELI5: "v8Engine" = "Engine that can drink 8 cups of java coffee" @Autowired @Qualifier("v8Engine") private Engine engine; } @Component("v8Engine") public class V8Engine extends Engine { // When we are not eco-friendly 😎 // Runs on fossil fuels made from real dinosaurs! } @Component("electricEngine") public class ElectricEngine extends Engine { // For greener pastures! 🌿 // Powered by unicorn magic and recycled stardust. }

No more wars of the roses. @Qualifier puts the crown on the head of V8Engine, making it the one true king.

Construction at work

@Autowired magic works on constructors as well. What you get is a neat and traceable injection, that feels like a walk in a well-organized park.

Refined example:

@Component public class Vehicle { private final Engine engine; // Your vehicle assembly line @Autowired public Vehicle(Engine engine) { this.engine = engine; // Fill 'er up, please! } }

Lo and behold! When Vehicle comes into existence, the engine is ready to roar, tank full, thanks to constructor injection.

The Advanced Guardian Leviosa (Spell)

@Autowired has impressive cousins that possess their unique jazz. Their family name? @Inject and @Resource.

Example to stun:

@Component public class Vehicle { // I like my engines like I like my coffee - electric! ⚑️ @Resource(name = "electricEngine") private Engine engine; }

Fancy a change from @Autowired flairs? @Resource by name connects the desired bean to the dot.

@Configuration: The high castle

Complex projects demand elegant management. @Configuration classes are knights in shining armour helping to manicure your bean configurations.

An example of chivalry:

@Configuration public class VehicleConfig { // "My precious," said your app to beans @Bean public Engine engine() { return new V8Engine(); } // Bean Land Vehicle Factory 🏭 @Bean public Vehicle vehicle(Engine engine) { return new Vehicle(engine); } }

Higher land vantages offer the best views. Similarly, beans defined in @Configuration classes offer mighty control on bean creation, and how they connect.

Visualization

Picture @Autowired as a smart universal phone charger (πŸ”Œ):

When you have a phone (πŸ“±) gasping its last charge πŸ”‹, no need to panic searching which charger will fit. `@Autowired`: πŸ“±βž‘οΈπŸ”Œ Finds the right charger and pumps in your 'juice'.

Playing it out:

Plug, play, and forget: 1. Plug your phone at the charging station (🏠). 2. **`@Autowired`** steps in, knowing its job. 3. Blazes your phone battery with power ⚑️.

Your Spring components, just like your phones, are always in full throttle with @Autowired.

Dodge the pitfalls in context scanning

If <context:component-scan> feels like standing on the shoulders of giants, ensure you're not wobbly:

  • Package listing must be meticulous.
  • Classpaths for third-party beans can't go AWOL.
  • Annotations on classes need to shine bright for auto-detection.

App-size decisions: Scopes and servlet context

There's comfort in company. That's why most Spring beans are singletons. Map your soldiers (components) interaction knowing this fact.

Servlet context in Spring is like the HQ managing bean definitions with the maps of XML configurations or Java-based @Configuration.

Staying modern

As time flows, so does Spring. JARs sink or swim with the Spring version wave, so do your tutorials.

XML configurations – the finest artist

For the art connoisseur, XML allows detailed bean-portraits:

  • When "less is more" rings hollow, specify fully qualified class names.
  • From Spring 3.x, <bean> tag's autowire attribute injects by-type, just emulating @Autowired.
  • Value and reference injections, simply work with <constructor-arg>.