Spring Core Annotations with Examples

In this quick article, we will discuss Spring core annotations that are used in Spring Dependency Injection, Java-based configuration, Annotation-based configuration, and Spring IOC. 

YouTube Video - Spring Core Annotations Explained with Examples

15 Important Spring Core Annotations

Let's list all known Spring core annotations.

Spring Core Annotations for Dependency Injection and Configuration

1. @Autowired Annotation

The @Autowired annotation is used for automatic dependency injection in Spring. It can be applied to constructors, fields, and setter methods.

Constructor Injection

@RestController
public class CustomerController {
    private final CustomerService customerService;

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

Setter Injection

@RestController
public class CustomerController {
    private CustomerService customerService;

    @Autowired
    public void setCustomerService(CustomerService customerService) {
        this.customerService = customerService;
    }
}

Field Injection

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

For more details, visit our articles on Spring @Autowired Annotation and Guide to Dependency Injection in Spring.

2. @Bean Annotation

The @Bean annotation indicates that a method produces a bean managed by the Spring container. It is typically declared in the configuration class.

@Configuration
public class AppConfig {

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

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

This configuration is equivalent to the following Spring XML:

<beans>
    <bean id="customerService" class="com.companyname.projectname.CustomerService"/>
    <bean id="orderService" class="com.companyname.projectname.OrderService"/>
</beans>

Read more about the @Bean annotation on Spring @Bean Annotation with Example.

3. @Qualifier Annotation

The @Qualifier annotation is used in conjunction with @Autowired to avoid confusion when multiple beans of the same type are configured.

Example

Consider EmailService and SMSService implementing a single MessageService interface.

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

@Component
public class EmailService implements MessageService {
    public void sendMsg(String message) {
        System.out.println("Email message: " + message);
    }
}

@Component
public class SMSService implements MessageService {
    public void sendMsg(String message) {
        System.out.println("SMS message: " + message);
    }
}

Using @Qualifier to inject specific implementations:

@Component
public class MessageProcessor {
    private final MessageService messageService;

    @Autowired
    @Qualifier("emailService")
    public MessageProcessor(MessageService messageService) {
        this.messageService = messageService;
    }

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

Read more on Spring @Qualifier Annotation Example.

4. @Required Annotation

The @Required annotation is a method-level annotation applied to the setter method of a bean. It indicates that the setter method must be configured with a value at configuration time.

Example

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

XML Configuration:

<bean class="com.javaguides.spring.Car">
    <property name="color" value="green"/>
</bean>

5. @Value Annotation

The @Value annotation is used to assign default values to variables and method arguments. It supports Spring Expression Language (SpEL) for complex expressions.

Example

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

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

@Value("#{systemProperties['java.home']}")
private String javaHomeSpel;

Read more on Spring @Value Annotation.

6. @DependsOn Annotation

The @DependsOn annotation forces the Spring IoC container to initialize one or more beans before the bean annotated with @DependsOn.

Example

public class FirstBean {
    @Autowired
    private SecondBean secondBean;
}

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

@Configuration
public class AppConfig {

    @Bean("firstBean")
    @DependsOn("secondBean")
    public FirstBean firstBean() {
        return new FirstBean();
    }

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

Read more on Spring @DependsOn Annotation Example.

7. @Lazy Annotation

The @Lazy annotation delays the initialization of a singleton bean until it is first requested.

Example

public class FirstBean {
    public void test() {
        System.out.println("Method of FirstBean Class");
    }
}

@Configuration
public class AppConfig {

    @Lazy
    @Bean
    public FirstBean firstBean() {
        return new FirstBean();
    }

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

Read more on Spring @Lazy Annotation Example.

8. @Lookup Annotation

A method annotated with @Lookup tells Spring to return an instance of the method’s return type when it is invoked.

Read more about the annotation in Spring @LookUp Annotation.

9. @Primary Annotation

The @Primary annotation gives higher preference to a bean when multiple beans of the same type exist.

Example

@Component
@Primary
public class Car implements Vehicle {}

@Component
public class Bike implements Vehicle {}

@Component
public class Driver {
    @Autowired
    private Vehicle vehicle;
}

Read more on Spring @Primary Annotation Example.

10. @Scope Annotation

The @Scope annotation defines the scope of a @Component class or a @Bean definition.

Example

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

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

Read more on Spring @Scope Annotation with Singleton Scope Example and Spring @Scope Annotation with Prototype Scope Example.

11. @Profile Annotation

The @Profile annotation is used to conditionally include @Component classes or @Bean methods based on the active profile.

Example

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

Read more on Spring Profiles.

12. @Import Annotation

The @Import annotation allows loading @Bean definitions from another configuration class.

Example

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

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

Read more on Spring @Import Annotation.

13. @ImportResource Annotation

The @ImportResource annotation loads beans from an applicationContext.xml file into the ApplicationContext.

Example

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

Read more on Spring @ImportResource Annotation.

14. @PropertySource Annotation

The @PropertySource annotation adds a PropertySource to Spring’s Environment.

Example

@Configuration
@PropertySource("classpath:config.properties")
public class PropertySourceDemo implements InitializingBean {

    @Autowired
    private Environment env;

    @Override
    public void afterPropertiesSet() throws Exception {
        setDatabaseConfig();
    }

    private void setDatabaseConfig() {
        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.to

String());
    }
}

Read more on Spring @PropertySource Annotation Example.

15. @ComponentScan Annotation

The @ComponentScan annotation configures component scanning directives for Spring to locate and register beans within the specified packages.

Example

@Configuration
@ComponentScan(basePackages = "com.example")
public class AppConfig {}

Read more on Spring @ComponentScan Annotation.

16. @SpringBootApplication Annotation

The @SpringBootApplication annotation marks the main class of a Spring Boot application. It combines the functionality of @Configuration, @EnableAutoConfiguration, and @ComponentScan.

Example

@SpringBootApplication
public class MySpringBootApplication {
    public static void main(String[] args) {
        SpringApplication.run(MySpringBootApplication.class, args);
    }
}

Read more on Spring @SpringBootApplication Annotation.

Conclusion

In this guide, we covered the fundamental Spring core annotations used for dependency injection, configuration, and managing the Spring IoC container. Understanding these annotations is crucial for effectively developing and configuring Spring applications. For further reading and deeper insights, follow the linked resources within each annotation section.

For more in-depth articles and examples, visit javaguides.net.

Comments