0% found this document useful (0 votes)
4 views10 pages

Annotation DI Spring 14

The document explains dependency injection in Spring, focusing on the use of the @Value and @Autowired annotations for injecting values and beans into Spring components. It details how to utilize properties files for configuration, the importance of providing default values for missing properties, and the differences in handling primitive and string types. Additionally, it emphasizes best practices for ensuring smooth application behavior when dealing with missing or commented properties.

Uploaded by

yograj.tripathi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views10 pages

Annotation DI Spring 14

The document explains dependency injection in Spring, focusing on the use of the @Value and @Autowired annotations for injecting values and beans into Spring components. It details how to utilize properties files for configuration, the importance of providing default values for missing properties, and the differences in handling primitive and string types. Additionally, it emphasizes best practices for ensuring smooth application behavior when dealing with missing or commented properties.

Uploaded by

yograj.tripathi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

Injecting Dependencies in Spring

Key Points:

1. @Component: We've utilized @Component to instantiate bean classes, enabling Spring


to manage their lifecycle.
2. Instance Variables: When a bean class has instance variables, they are initialized with
their default values upon object creation.
3. Dependency Injection: Spring offers two annotations for injecting values into instance
variables:
○ @Value: Used for injecting literal values or values from properties files.
○ @Autowired: Used for injecting other beans into a bean, facilitating inter-bean
dependencies.

Notes: The @Value Annotation


Key Points:

● Purpose: Primarily used for assigning default values to instance variables and method
parameters.
● Functionality: Also allows developers to inject values from property files into class
members.

In Summary:

The @Value annotation is a versatile tool for setting default values and injecting external
properties into Spring beans.

The @Value Annotation in Spring

Key Points:

● Purpose: Primarily used for assigning default values to instance variables and method
parameters.
● Functionality: Enables developers to inject values from property files into class
members.

In Summary:
The @Value annotation is a versatile tool for setting default values and injecting external
properties into Spring beans.

Injecting Values Directly

Using @Value Annotation:


Syntax:
java
Copy code
@Value("value to be injected")

Important Points:

● The @Value annotation can be applied at:


○ Field level: Directly on instance variables.
○ Method level: Along with method parameters or constructor arguments.
● The value to be injected must be enclosed in quotes ("..."), and Spring will
automatically convert it according to the type of the variable. If conversion fails, an
exception will be thrown.

Using @Value with Methods


Topic: Using @Value with Methods in Spring

Key Points:

1. Method Invocation: Spring will automatically call a method annotated with @Value after
creating the bean.
2. Method Name: The method name can be any valid name, not necessarily a setter
method.

Example:

Java
@Component
public class Student {

private int roll;


private String name;

public Student() {
System.out.println("Creating Student");
}

@Value("25")
public void setRoll(int roll) {
this.roll = roll;
System.out.println("Setter for roll called");
}

// ... other methods


}
Use code with caution.

Explanation:

In this example, the setRoll method is annotated with @Value("25"). When the Student
bean is created, Spring will automatically call the setRoll method and assign the value "25" to
the roll instance variable.

Additional Notes:

● You can use @Value with any method, not just setters.
● You can use expressions or SpEL (Spring Expression Language) within the @Value
annotation.
● You can inject values from property files using @Value("${property.name}").

@Value Annotation and Setter Methods in Spring


In Spring, when we use the @Value annotation:

● If @Value("...") is applied, the setter method is automatically invoked, and the


value is injected as specified.
● Without the @Value annotation, the setter method will not be called automatically,
and no value will be set unless explicitly done in the code.

This means that @Value ensures automatic injection and invocation of the setter, while its
absence prevents automatic initialization.
Using @Value With Constructor in Spring
Key Points:

1. @Value is Compulsory for Primitives in Constructor:


If a class is annotated with @Component and its constructor accepts primitive types,
then it is mandatory to use the @Value annotation for those parameters to inject values.
2. @Value Cannot Be Placed Above the Constructor:
Unlike methods, the @Value annotation cannot be applied at the top of a constructor.
Instead, it must be used with each constructor parameter.
3. Recommended for Dependency Injection:
Using @Value with constructor parameters is a common and recommended practice for
injecting values into beans, especially for primitive types.

In Summary:

● Constructor Parameter Injection: @Value must be applied to individual constructor


parameters, not on top of the constructor itself.
● Mandatory for Primitives: When injecting primitive types via constructor in a
@Component-annotated class, @Value is essential for proper dependency injection.
Using Properties Files in Spring and @Value
Annotation
Key Annotations:

1. @Configuration: Marks the class as a source of bean definitions and configuration in


Spring.
2. @ComponentScan: Enables component scanning, so Spring can find and register
beans automatically.
3. @PropertySource: Used to define the location of the properties file that contains
key-value pairs for configuration.

Introducing Properties File in Spring

1. What is a Properties File?


○ A properties file in Spring is a configuration file with key-value pairs that store
application settings, configuration parameters, or other externalized data.
○ It typically has a .properties extension and is a simple text file.
○ Advantage: Separates configuration from the application code, allowing easy
management across different environments (like development, testing,
production) without recompiling the code.
2. Why Use Properties Files?
○ If any settings change in the properties file, the Java class doesn't need to be
recompiled.
○ Properties files help maintain flexible and easily configurable applications.

Using @Value to Read Properties


Syntax:
To read a property from a properties file, use the @Value annotation in your Java class:
java
Copy code
@Value("${key}")

1.
2. Example:

In your .properties file:


properties
Copy code
student.name=Amit


In your Java Component class:
java
Copy code
@Value("${student.name}")
private String studentName;

The @PropertySource Annotation

1. Purpose:
The @PropertySource annotation is used to specify the location of the properties file
containing key-value pairs that you want to inject into Spring beans using the @Value
annotation.
2. Where to Use @PropertySource:
○ The @PropertySource annotation is applied in the @Configuration class.

Syntax:
java

Copy code
@PropertySource("classpath:application.properties")
public class AppConfig {
// Bean definitions and configuration settings
}

3.

Complete Example for Better Understanding

1. Properties File (application.properties):

properties
Copy code
student.name=Rahul
student.roll=101

2. Configuration Class (AppConfig.java):

java
Copy code
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

@Configuration
@ComponentScan(basePackages = "com.example")
@PropertySource("classpath:application.properties")
public class AppConfig {
// Configuration settings and beans
}

3. Component Class (Student.java):

java
Copy code
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class Student {

@Value("${student.name}")
private String name;

@Value("${student.roll}")
private int roll;

public void display() {


System.out.println("Name: " + name);
System.out.println("Roll: " + roll);
}
}

Explanation:

● The properties file defines values for student.name and student.roll.


● The @PropertySource in AppConfig tells Spring where to find the properties file.
● The @Value annotation is used in the Student class to inject the property values into
instance variables
Handling Missing or Commented Properties in
Spring with @Value
Key Points:

1. Primitive Types (e.g., int, double):


○ If a primitive type like int or double is expected in the constructor via
@Value, Spring requires that the corresponding key in the properties file
must have a value.
○ If the value is missing or commented out in the properties file, Spring will
throw an exception such as NoSuchElementException or
NumberFormatException because it cannot inject null into a primitive.
○ Example:
■ If student.roll is missing in the properties file, Spring won't be able to
inject a value, resulting in an error.
2. String Types:
○ For String parameters, Spring allows the injection of null if the property is
missing or commented out. This means no exception will be thrown, and the
variable will be set to null.
○ Example:
■ If student.name is commented out, Spring will inject null into the
name parameter without causing an error.
3. Best Practices:

To avoid exceptions for primitive types, use a default value in the @Value annotation to handle
missing properties gracefully:
java
Copy code
@Value("${student.roll:0}") // 0 as the default value

For String types, you can either allow null or provide a default value:
java
Copy code
@Value("${student.name:Unknown}") // "Unknown" as the default value

Summary:

● Primitive types require values in the properties file, or a default value should be
provided.
● String types can handle null values if a property is missing, and it’s best to provide a
default value when needed.
Handling Missing Property Values in Spring with
Default Values
To handle missing or commented-out properties in Spring, we can provide default values using
the @Value annotation. This ensures that the application doesn't throw an exception when a
property is missing or commented out in the .properties file.

Example Solution:
java
Copy code
public Student(@Value("${student.roll}") int roll,
@Value("${student.name:Guest}") String name) {
this.roll = roll;
this.name = name;
System.out.println("Student constructor called!");
}

Key Points:

1. Primitive Types (int):


○ The @Value("${student.roll}") annotation does not have a default value,
meaning that if the student.roll property is missing, Spring will throw an
exception.

To avoid this, you can specify a default value like:


java
Copy code
@Value("${student.roll:0}") // Default value of 0


2. String Types (String):
○ In this example, the student.name property uses
@Value("${student.name:Guest}"), meaning that if student.name is
missing or commented out in the .properties file, the default value "Guest"
will be used.
○ This helps avoid any issues with missing String properties.

Summary:

● Primitive types must have values defined in the properties file, or you need to provide a
default value to avoid exceptions.
● String types can handle missing values by using the @Value annotation with a default
value, ensuring the program runs smoothly even if a property is missing.

You might also like