Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Spring @Autowired and @Inject annotations

    • 0
    • 1
    • 1
    • 2
    • 0
    • 0
    • 0
    • 0
    • 536
    Comment on it

    @Autowired and @Inject Annotations in Spring framework :

    @Autowired : The power of Spring Framework is dependency injection and this dependency injection is done using the configuration file. All beans are registered in that configuration file and then container instantiate those beans and inject beans if there is any dependencies. Spring bean configuration refer the injected bean using the "ref" attribute but Spring framework provides autowiring feature, so that you don't need to explicitly define dependency injection using "ref" attribute. Autowiring can be done using three ways byName, byType and constructor attribute. Spring also provides @Autowired annotation for autowiring the bean.

    For @Autowired annotation to work, we need to enable annotation based configuration in bean configuration file. To enable it write <context:annotation-config/> in configuration file.

    You can put @Autowired annotation on the top of property name or the setXXX() method. The container will scan the bean and if find the @Autowired annotation above any property, then it will search for the bean by its type in the configuration file and if found then inject it to the bean otherwise throw the exception.

    Example of @Autowired annotation:

    College.java

    package com.evon.example.autowire&#95;inject;
    public class College {
        private String collegeName;
    
        public String getCollegeName() {
            return collegeName;
        }
        public void setCollegeName(String collegeName) {
            this.collegeName = collegeName;
        }
    }
    

    Student.java

    package com.evon.example.autowire&#95;inject;
    import org.springframework.beans.factory.annotation.Autowired;
    public class Student {
        private String studName;
        private String  age;
    
        @Autowired
        private College college;
    
        public String getStudName() {
            return studName;
        }
        public void setStudName(String studName) {
            this.studName = studName;
        }
        public String getAge() {
            return age;
        }
        public void setAge(String age) {
            this.age = age;
        }   
        public College getCollege() {
            return college;
        }   
        public void setCollege(College college) {
            this.college = college;
        }
    }
    

    bean.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns:c="http://www.springframework.org/schema/c"
      xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
    http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd">
    
    <context:annotation-config/> 
    <context:component-scan base-package="com.evon.example.autowire&#95;inject"/> 
        <bean id="collegeBean" class="com.evon.example.autowire&#95;inject.College">
            <property name="collegeName" value="MIT"/>
        </bean>  
    
        <bean id="studentBean" class="com.evon.example.autowire&#95;inject.Student">
            <property name="studName" value="Rahul"/>
            <property name="age" value="22"/>
        </bean>  
    </beans>
    

    Main.java

    package com.evon.example.autowire&#95;inject;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.FileSystemXmlApplicationContext;
    public class Main {
        public static void main(String[] args) {
            ApplicationContext context = new FileSystemXmlApplicationContext("/src/main/java/com/evon/example/autowire&#95;inject/bean.xml");
            Student student = (Student)context.getBean("studentBean");
            System.out.println("Student Name : "+student.getStudName());
            System.out.println("Student Age : "+student.getAge());
            System.out.println("College Name : "+student.getCollege().getCollegeName());
        }
    }
    

    Output:

    Student Name : Rahul
    Student Age : 22
    College Name : MIT
    

    You can also put @Autowire annotation on the constructor, by this the dependency will be injected using constructor.

    @Autowired with constructor:

    Student.java

    package com.evon.example.autowire&#95;inject;
    import org.springframework.beans.factory.annotation.Autowired;
    public class Student {
        private String studName;
        private String  age;    
        private College college;
    
        @Autowired(required=true)
        Student(College college){
            this.college = college; 
        }
        public String getStudName() {
            return studName;
        }
        public void setStudName(String studName) {
            this.studName = studName;
        }
        public String getAge() {
            return age;
        }
        public void setAge(String age) {
            this.age = age;
        }   
        public College getCollege() {
            return college;
        }   
        public void setCollege(College college) {
            this.college = college;
        }
    }
    

    @Autowired with (required=false) option :

    By default the @Autowired constructor having the property required=true. If we apply the Autowired on any property it will search for that bean to inject, if not found the it will through an exception. But if we don't want to mandatory that field and don't want to handle exception then we can apply the @Autowired with attribute required=false.

    @Autowired(reuired=false) Example:

    package com.evon.example.autowire&#95;inject;
    import org.springframework.beans.factory.annotation.Autowired;
    public class Student {
        private String studName;
        private String  age;    
        private College college;
        /*@Autowired(required=false)
        Student(College college){
            this.college = college;
        }*/
    
        public String getStudName() {
            return studName;
        }
        public void setStudName(String studName) {
            this.studName = studName;
        }
        public String getAge() {
            return age;
        }
        public void setAge(String age) {
            this.age = age;
        }
    
        public College getCollege() {
            return college;
        }
    
        @Autowired(required=false)
        public void setCollege(College college) {
            this.college = college;
        }
    }
    

    @Inject annotation in Spring: @Autowired and @Inject annotations are almost same, both the annotations are used to automatic detection and injecting the bean.Both of these annotations use the AutowiredAnnotationBeanPostProcessor class to inject bean dependencies. @Inject is a java base annotation and also can say JSR-330 standard annotation. Spring supports the JSR-330 standard annotations. Because of @Inject is a java standard annotation, It is preferred over the @Autowired, because if you want to port your application from spring framework to other framework @Autowire will not work but @Inject will work fine. To use @Inject(javax.inject.Inject) annotation you need to download the "javax.inject-1.jar" or put the following dependency in your pom.xml:

    <dependency>
        <groupId>javax.inject</groupId>
        <artifactId>javax.inject</artifactId>
        <version>1</version>
    </dependency>
    

    Example of @Inject annotation :

    package com.evon.example.autowire&#95;inject;
    import org.springframework.beans.factory.annotation.Autowired;
    public class Student {
        private String studName;
        private String  age;    
        private College college;
    
        public String getStudName() {
            return studName;
        }
        public void setStudName(String studName) {
            this.studName = studName;
        }
        public String getAge() {
            return age;
        }
        public void setAge(String age) {
            this.age = age;
        }       
        public College getCollege() {
            return college;
        }
    
        @Inject
        public void setCollege(College college) {
            this.college = college;
        }
    }
    

    Limitations on JSR-330 :

    1. @Inject has no required attribute to make sure the bean is injected successfully.
    2. In Spring container, JSR-330 has scope singleton by default, but you can use Springs @Scope to define others.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: