user9143182
user9143182

Reputation:

Why are annotations used with java on Dependecy Injection

so I am reading about the Dependency Injection for the first time. I think I have figured it out and I have understood an example written for PHP. Though, I was reading this JAVA tutorial and it insists on adding annotations. If I am going to offer the the class its dependency externally using the constructor for example, then what why are the annotations required? Also, I am reading on the Spring framework, which also states you need annotations. How do the annotations fit in? Any information is appreciated.

Upvotes: 0

Views: 54

Answers (1)

Amit Bhati
Amit Bhati

Reputation: 5649

what why are the annotations required?

This is up to you, whether you want an XML configuration or annotations. Spring uses annotations as an alternative to XML for declarative configuration.

Let's take your example,you want to pass dependency through constructor.
Department object has dependency on Employee object for its creation.
Employee object has two attributes id and name.

  1. By using annotation how Can you do it?

    @Configuration
    @ComponentScan("com.example.spring")
    public class Config {
    
        @Bean
    public Employee employee() {
        return new Employee("1", "John");
    }
    }
    

Now creating Department object:

@Component
public class Department {

    @Autowired
    public Department (Employee employee) {
        this.employee= employee;

    }
}
  1. By using XML:

    <beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
    
    <bean id="department" class="com.example.spring.Department">
        <constructor-arg index="0" ref="employee"/>
    </bean>
    
    <bean id="employee" class="com.example.spring.Employee">
        <constructor-arg index="0" value="1"/>
        <constructor-arg index="1" value="John"/>
    </bean>
    

  2. By using Java: You can do something like

     Employee employee=new Employee("1","John");   
     Department dept=new Department(employee);
    

Point is, It's up-to you how you want to do things.

Have a look at this question Xml configuration versus Annotation based configuration

Upvotes: 2

Related Questions