Quick Contact

    Hibernate

    Spring Core Annotations

    Here, we will discuss Spring core annotations that are used in Spring DI and Spring IOC. As we know Spring DI and Spring IOC are core concepts of Spring Framework. These Spring core annotations we will explore

    from org.springframework.beans.factory.annotation and org.springframework.context.annotation packages.

    @Autowired

    We can use the @Autowired to mark a dependency which Spring is going to resolve and inject. We can use this annotation with a constructor, setter, or field injection.

    Constructor Injection:

    @RestController
    publicclassCustomerController {
    privateCustomerServicecustomerService;
    
    @Autowired
    publicCustomerController(CustomerServicecustomerService) {
    this.customerService=customerService;
        }
    }
    

    Setter Injection:

    importorg.springframework.beans.factory.annotation.Autowired;
    importorg.springframework.web.bind.annotation.RestController;
    
    @RestController
    publicclassCustomerController {
    privateCustomerServicecustomerService;
    
    @Autowired
    publicvoidsetCustomerService(CustomerServicecustomerService) {
    this.customerService=customerService;
        }
    }
    

    Field Injection:

    importorg.springframework.beans.factory.annotation.Autowired;
    importorg.springframework.web.bind.annotation.RestController;
    
    @RestController
    publicclassCustomerController {
    @Autowired
    privateCustomerServicecustomerService;
    }
    

    @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 init-method, destroy-method, autowiring and name.
      • You can use the @Bean annotation in a @Configuration-annotated or in a @Component-annotated class.

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

    importorg.springframework.context.annotation.Bean;
    importorg.springframework.context.annotation.Configuration;
    
    importcom.companyname.projectname.customer.CustomerService;
    importcom.companyname.projectname.order.OrderService;
    
    @Configuration
    publicclassApplication {
    
    @Bean
    publicCustomerServicecustomerService() {
    returnnewCustomerService();
        }
    
    @Bean
    publicOrderServiceorderService() {
    returnnewOrderService();
        }
    }
    

    The preceding configuration is exactly equivalent to the following Spring XML:

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

    @Qualifier

    This annotation helps fine-tune annotation-based autowiring. 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 @Qualifier annotation along with the @Autowired annotation.

    Example: Consider EmailService and SMSService classes implements single MessageService interface.

    Create MessageService interface for multiple message service implementations.

    publicinterfaceMessageService {
    publicvoidsendMsg(Stringmessage);
    }
    

    Create implementations – EmailService and SMSService.

    publicclassEmailServiceimplementsMessageService{
    
    publicvoidsendMsg(Stringmessage) {
    System.out.println(message);
        }
    }
    publicclassSMSServiceimplementsMessageService{
    
    publicvoidsendMsg(Stringmessage) {
    System.out.println(message);
        }
    }
    

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

    publicinterfaceMessageProcessor {
    publicvoidprocessMsg(Stringmessage);
    }
    
    publicclassMessageProcessorImplimplementsMessageProcessor {
    
    privateMessageServicemessageService;
    
    // setter based DI
    @Autowired
    @Qualifier("emailService")
    publicvoidsetMessageService(MessageServicemessageService) {
    this.messageService=messageService;
        }
    
    // constructor based DI
    @Autowired
    publicMessageProcessorImpl(@Qualifier("emailService") MessageServicemessageService) {
    this.messageService=messageService;
        }
    
    publicvoidprocessMsg(Stringmessage) {
    messageService.sendMsg(message);
        }
    }
    

    @Required

    The @Required annotation is 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 to mark dependencies that we want to populate through XML:

    @Required

    voidsetColor(String color) {
    this.color= color;
    }
    < beanclass="com.javaguides.spring.Car">
    < propertyname="color"value="green" />
    < /bean>
    

    Otherwise, BeanInitializationException will be thrown.

    @Value

    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 @Value annotation.

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

    Examples:

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

    @Value("Default DBConfiguration")
    privateStringdefaultName;
    

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

    @Value("true")
    privatebooleandefaultBoolean;
    
    @Value("10")
    privateintdefaultInt;
    

    Spring @Value – Spring Environment Property

    @Value("${APP_NAME_NOT_FOUND}")
    privateStringdefaultAppName;
    

    Assign system variables using @Value annotation.

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

    Spring @Value – SpEL

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

    @DependsOn

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

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

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

    publicclassFirstBean {
    
    @Autowired
    privateSecondBeansecondBean;
    }
    
    publicclassSecondBean {
    publicSecondBean() {
    System.out.println("SecondBean Initialized via Constuctor");
        }
    }
    

    Declare the above beans in java based configuration class.

    @Configuration
    publicclassAppConfig {
    
    @Bean("firstBean")
    @DependsOn(value= {
    "secondBean"
        })		
    publicFirstBeanfirstBean() {
    returnnewFirstBean();
        }
    
    @Bean("secondBean")
    publicSecondBeansecondBean() {
    returnnewSecondBean();
        }
    }
    

    @Lazy

    By default, the Spring IoC container creates and initializes all singleton beans at 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 @Component, or on methods annotated with @Bean.

    Example: Consider we have below two beans – FirstBean and SecondBean. In this example, we will explicitly load FirstBean using @Lazy annotation.

    publicclassFirstBean {
    publicvoidtest() {
    System.out.println("Method of FirstBean Class");
        }
    }
    publicclassSecondBean {
    publicvoidtest() {
    System.out.println("Method of SecondBean Class");
        }
    }
    

    Declare the above beans in java based configuration class.

    @Configuration
    publicclassAppConfig {
    
    @Lazy(value=true)
    @Bean
    publicFirstBeanfirstBean() {
    returnnewFirstBean();
        }
    
    @Bean
    publicSecondBeansecondBean() {
    returnnewSecondBean();
        }
    }
    

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

    @Primary

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

    @Component
    @Primary
    classCarimplementsVehicle {}
    
    @Component
    classBikeimplementsVehicle {}
    
    @Component
    classDriver {
    @Autowired
    Vehiclevehicle;
    }
    
    @Component
    classBiker {
    @Autowired
    @Qualifier("bike")
    Vehiclevehicle;
    }
    

     

    Apply now for Advanced Java Training Course

    Copyright 1999- Ducat Creative, All rights reserved.

    Anda bisa mendapatkan server slot online resmi dan terpercaya tentu saja di sini. Sebagai salah satu provider yang menyediakan banyak pilihan permainan.