15 Spring Core Annotation Examples – DZone Java | xxx15 Spring Core Annotation Examples – DZone Java – xxx
菜单

15 Spring Core Annotation Examples – DZone Java

十月 13, 2018 - MorningStar

Over a million developers have joined DZone.
15 Spring Core Annotation Examples - DZone Java

{{announcement.body}}

{{announcement.title}}

Let’s be friends:

15 Spring Core Annotation Examples

DZone’s Guide to

15 Spring Core Annotation Examples

Want to learn more about the top 15 Spring core annotations? Check out this post to see the best 15 annotations with example code.

Nov. 01, 18 · Java Zone ·

Free Resource

Join the DZone community and get the full member experience.

Join For Free

Get the Edge with a Professional Java IDE. 30-day free trial.

As we know, Spring DI and Spring IOC are core concepts of the Spring Framework. Let’s explore some Spring core annotations from the org.springframework.beans.factory.annotation and org.springframework.context.annotation packages.

We often call these “Spring core annotations,” and we’ll review them in this article.

Here’s a list of all known Spring core annotations.

15 Spring Core Annotation Examples - DZone Java

@Autowired

We can use the @Autowired annotation to mark the dependency that Spring is going to resolve and inject. We can use this annotation with a 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; }

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

@Bean

  •  @Bean is a method-level annotation and a direct analog of the XML element. The annotation supports some of the attributes offered by, such as the init-method, destroy-method, auto-wiring, and name.
  • You can use the  @Bean annotation in a  @Configuration-annotated or @Component-annotated class.

The following is a simple example of an @Bean method declaration:

import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration;  import com.companyname.projectname.customer.CustomerService; import com.companyname.projectname.order.OrderService;  @Configuration public class Application {      @Bean     public CustomerService customerService() {         return new CustomerService();     }      @Bean     public OrderService orderService() {         return new OrderService();     } }

The preceding 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 in this article  Spring @Bean Annotation with Example.

@Qualifier

This annotation helps fine-tune annotation-based auto-wiring. There may be scenarios when we create more than one bean of the same type and want to wire only one of them with a property. This can be controlled using the @Qualifier annotation along with the  @Autowired annotation.

Example: Consider the EmailService and SMSService classes to implement the single  MessageService interface.

Create the MessageService interface for multiple message service implementations.

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

Next, create implementations:  EmailService and SMSService.

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);     } }

It’s time to see the usage of the @Qualifier annotation.

public interface MessageProcessor {     public void processMsg(String message); }  public class MessageProcessorImpl implements MessageProcessor {      private MessageService messageService;      // setter based DI     @Autowired     @Qualifier("emailService")     public void setMessageService(MessageService messageService) {         this.messageService = messageService;     }      // constructor based DI     @Autowired     public MessageProcessorImpl(@Qualifier("emailService") MessageService messageService) {         this.messageService = messageService;     }      public void processMsg(String message) {         messageService.sendMsg(message);     } }

Read more about this annotation in this article:  Spring @Qualifier Annotation Example.

@Required

The @Required annotation is a method-level annotation and applied to the setter method of a bean.

This annotation simply indicates that the setter method must be configured to be dependency-injected with a value at configuration time.

For example, @Required on setter methods marks dependencies that we want to populate through XML:

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

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;     } }

0

Otherwise, the  BeanInitializationException will be thrown.

@Value

The Spring @Value annotation is used to assign default values to variables and method arguments. We can read Spring environment variables as well as system variables using the @Value annotation.

The Spring @Value annotation also supports SpEL. Let’s look at some of the examples of using the @Value annotation.

Examples: We can assign a default value to a class property using the @Value annotation.

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;     } }

1

The @Value annotation argument can be a string only, but Spring tries to convert it to the specified type. The following code will work fine and assign the boolean and integer values to the variable.

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;     } }

2

This demonstrates the Spring  @Value — Spring Environment Property

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;     } }

3

Next, assign system variables using the @Value annotation.

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;     } }

4

Spring @Value  – SpEL

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;     } }

5

@DependsOn

The@DependsOn annotation can force Spring IoC containers to initialize one or more beans before the bean, which is annotated by the  @DependsOn annotation.

The @DependsOn annotation may be used on any class directly or indirectly annotated with the  @Component or on methods annotated with the @Bean.

Example: Let’s create  FirstBean and  SecondBean classes. In this example, the  SecondBean is initialized before bean  FirstBean.

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;     } }

6

Declare the above beans in Java based on the configuration class.

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;     } }

7

Read more about @DependsOn annotation on Spring – @DependsOn Annotation Example.

@Lazy

By default, the Spring IoC container creates and initializes all singleton beans at the time of application startup. We can prevent this pre-initialization of a singleton bean by using the @Lazy annotation.

The  @Lazy annotation may be used on any class, directly or indirectly annotated with the  @Component or on methods annotated with the @Bean.

Example: Consider we have below two beans — FirstBean and  SecondBean. In this example, we will explicitly load  FirstBean using the  @Lazyannotation.

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;     } }

8

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;     } }

9

Declare the above beans in Java based on the configuration class.

import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RestController;  @RestController public class CustomerController {     @Autowired     private CustomerService customerService; }

0

As we can see, bean secondBean is initialized by the Spring container, while the bean firstBean is initialized explicitly.

Read more about the  @Lazy  annotation with a complete example on Spring – @Lazy Annotation Example.

@Lookup

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

Detailed information about this annotation can be found on Spring @LookUp Annotation.

@Primary

We use the  @Primary to give higher preference to a bean when there are multiple beans of the same type.

import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RestController;  @RestController public class CustomerController {     @Autowired     private CustomerService customerService; }

1

Read more about this annotation on Spring – @Primary Annotation Example.

@Scope

We use the@Scope annotation to define the scope of a  @Component class or the @Bean definition. It can be either singleton, prototype, request, session, globalSession, or some custom scope.

For example:

import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RestController;  @RestController public class CustomerController {     @Autowired     private CustomerService customerService; }

2

Read more about the @Scope annotations on Spring @Scope annotation with Singleton Scope Example and Spring @Scope annotation with Prototype Scope Example.

@Profile

If we want Spring to use the @Component class or the @Bean method only when a specific profile is active, we can mark it with  @Profile. We can configure the name of the profile with the value argument of the annotation:

import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RestController;  @RestController public class CustomerController {     @Autowired     private CustomerService customerService; }

3

You can read more about profiles in this Spring Profiles.

@Import

The  @Import annotation indicates one or more @Configuration classes to import.

For example: in a Java-based configuration, Spring provides the @Import  annotation, which allows the loading @Bean definitions from another configuration class.

import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RestController;  @RestController public class CustomerController {     @Autowired     private CustomerService customerService; }

4

Now, rather than needing to specify both the ConfigA class and ConfigB class when instantiating the context, only ConfigB needs to be supplied explicitly.

Read more about the @Import annotation on Spring @Import Annotation.

@ImportResource

Spring provides an @ImportResource annotation used to load beans from an applicationContext.xml file into an ApplicationContext. For example: consider that we have applicationContext.xml Spring bean configuration XML file on the classpath.

import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RestController;  @RestController public class CustomerController {     @Autowired     private CustomerService customerService; }

5

Read more about this annotation with a complete example on Spring @ImportResource Annotation.

@PropertySource

The  @PropertySource annotation provides a convenient and declarative mechanism for adding a PropertySource to Spring’s Eenvironment to be used in conjunction with the @Configuration classes.

For example, we are reading database configuration from the file config.propertiesfile and setting these property values to the DataSourceConfig class using the Environment.

import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RestController;  @RestController public class CustomerController {     @Autowired     private CustomerService customerService; }

6

Read more about this annotation on Spring @PropertySource Annotation with Example.

@PropertySources

We can use this annotation to specify multiple  @PropertySource  configurations:

import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RestController;  @RestController public class CustomerController {     @Autowired     private CustomerService customerService; }

7

Read more about this annotation on Spring @PropertySources Annotation.

Hope you enjoyed this post on the best Spring annotations for your project! Happy coding!

Get the Java IDE that understands code & makes developing enjoyable. Level up your code with IntelliJ IDEA. Download the free trial.

Topics:
Java ,Spring ,annotations ,Spring Core ,beans ,configurations ,dependencies ,bean

Opinions expressed by DZone contributors are their own.

Java Partner Resources

Red Hat Developer Program

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.linkDescription }}

{{ parent.urlSource.name }}

· {{ parent.articleDate | date:’MMM. dd, yyyy’ }} {{ parent.linkDate | date:’MMM. dd, yyyy’ }}


Notice: Undefined variable: canUpdate in /var/www/html/wordpress/wp-content/plugins/wp-autopost-pro/wp-autopost-function.php on line 51