Master Spring Core Annotations: @Autowired, @Bean, @Qualifier, @Value and More

This article provides a comprehensive guide to Spring's core annotations—including @Autowired, @Bean, @Qualifier, @Required, @Value, @DependsOn, @Lazy, @Lookup, @Primary, @Scope, @Profile, @Import, @ImportResource, @PropertySource and @PropertySources—explaining their purpose, usage patterns, and code examples for constructor, setter, and field injection in Java applications.

Programmer DD
Programmer DD
Programmer DD
Master Spring Core Annotations: @Autowired, @Bean, @Qualifier, @Value and More

@Autowired

The @Autowired annotation marks a dependency for Spring to resolve and inject. It can be used with constructor, setter, or field injection.

Constructor Injection

@RestController
public class CustomerController {
    private CustomerService customerService;
    @Autowired
    public CustomerController(CustomerService customerService) {
        this.customerService = customerService;
    }
}

Setter Injection

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class CustomerController {
    private CustomerService customerService;
    @Autowired
    public void setCustomerService(CustomerService customerService) {
        this.customerService = customerService;
    }
}

Field Injection

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class CustomerController {
    @Autowired
    private CustomerService customerService;
}

@Bean

@Bean is a method‑level annotation that mimics an XML <bean> element. It can be used inside @Configuration or @Component classes.

@Configuration
public class Application {
    @Bean
    public CustomerService customerService() {
        return new CustomerService();
    }

    @Bean
    public OrderService orderService() {
        return new OrderService();
    }
}

@Qualifier

@Qualifier fine‑tunes autowiring when multiple beans of the same type exist. It works together with @Autowired.

public interface MessageService {
    void sendMsg(String message);
}

public class EmailService implements MessageService {
    public void sendMsg(String message) { System.out.println(message); }
}

public class SMSService implements MessageService {
    public void sendMsg(String message) { System.out.println(message); }
}

@Component
public class MessageProcessorImpl implements MessageProcessor {
    @Autowired
    @Qualifier("emailService")
    private MessageService messageService;

    public void processMsg(String message) {
        messageService.sendMsg(message);
    }
}

@Required

@Required is a method‑level annotation applied to a bean's setter to indicate that the property must be injected, otherwise a BeanInitializationException is thrown.

@Required
public void setColor(String color) {
    this.color = color;
}

@Value

@Value injects default values into fields or method parameters, supporting property placeholders and SpEL expressions.

@Value("Default DBConfiguration")
private String defaultName;

@Value("true")
private boolean defaultBoolean;

@Value("10")
private int defaultInt;

@Value("${APP_NAME_NOT_FOUND}")
private String defaultAppName;

@Value("${java.home}")
private String javaHome;

@Value("${HOME}")
private String homeDir;

@DependsOn

@DependsOn forces the initialization order of beans, ensuring that the specified beans are created before the annotated bean.

@Component
public class FirstBean {
    @Autowired
    private SecondBean secondBean;
}

@Component
public class SecondBean {
    public SecondBean() {
        System.out.println("SecondBean Initialized via Constructor");
    }
}

@Lazy

@Lazy delays the initialization of singleton beans until they are first needed.

@Configuration
public class AppConfig {
    @Lazy(true)
    @Bean
    public FirstBean firstBean() {
        return new FirstBean();
    }

    @Bean
    public SecondBean secondBean() {
        return new SecondBean();
    }
}

@Lookup

@Lookup tells Spring to return a fresh instance of the method's return type each time the method is called.

@Primary

@Primary gives higher priority to a bean when multiple candidates of the same type exist.

@Component
@Primary
class Car implements Vehicle {}

@Component
class Bike implements Vehicle {}

@Component
class Driver {
    @Autowired
    private Vehicle vehicle; // Car will be injected because it is @Primary
}

@Scope

@Scope defines the lifecycle of a bean (singleton, prototype, request, session, etc.).

@Component
@Scope(ConfigurableBeanFactory.SCOPE_SINGLETON)
class TwitterMessageService implements MessageService {}

@Component
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
class TwitterMessageService implements MessageService {}

@Profile

@Profile activates a component or @Bean only when the specified profile is active.

@Component
@Profile("sportDay")
class Bike implements Vehicle {}

@Import

@Import brings one or more @Configuration classes into the current configuration.

@Configuration
class ConfigA {
    @Bean
    public A a() { return new A(); }
}

@Configuration
@Import(ConfigA.class)
class ConfigB {
    @Bean
    public B b() { return new B(); }
}

@ImportResource

@ImportResource loads bean definitions from an XML file into the ApplicationContext.

@Configuration
@ImportResource({"classpath*:applicationContext.xml"})
class XmlConfiguration {}

@PropertySource & @PropertySources

@PropertySource adds a property file to Spring's Environment; @PropertySources allows multiple files.

@Configuration
@PropertySource("classpath:config.properties")
public class ProperySourceDemo implements InitializingBean {
    @Autowired
    private Environment env;

    @Override
    public void afterPropertiesSet() throws Exception {
        DataSourceConfig config = new DataSourceConfig();
        config.setDriver(env.getProperty("jdbc.driver"));
        config.setUrl(env.getProperty("jdbc.url"));
        config.setUsername(env.getProperty("jdbc.username"));
        config.setPassword(env.getProperty("jdbc.password"));
        System.out.println(config);
    }
}

@PropertySources({
    @PropertySource("classpath:config.properties"),
    @PropertySource("classpath:db.properties")
})
public class AppConfig { }
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

springbeandependency-injection
Programmer DD
Written by

Programmer DD

A tinkering programmer and author of "Spring Cloud Microservices in Action"

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.