SpringNotesByPawan
SpringNotesByPawan
class. In the Employee class, there are three main places where @Autowired can be applied:
You’ve already used @Autowired on the address field in the Employee class. Here’s how it
works:
@Autowired
private Address address; // Dependency to be injected by Spring
Explanation:
Spring will look for a bean of type Address in the application context and inject it
into the address field.
This approach is simple and concise but makes the field difficult to test as it cannot be
set manually.
2. Setter Injection
You can use @Autowired on the setter method for the address field.
Code Example:
@Autowired
public void setAddress(Address address) {
this.address = address;
}
Explanation:
Spring will call this setter method and pass the Address bean to it.
Setter injection is useful when you want to allow optional dependencies or change the
dependency at runtime.
3. Constructor Injection
Code Example:
@Autowired
public Employee(Address address) {
this.address = address;
}
Explanation:
Spring will automatically inject the Address bean when creating the Employee bean.
Constructor injection ensures that the dependency is provided at the time of object
creation, making the class immutable and easier to test.
Preferred approach when the dependency is mandatory.
Here’s how your Employee class could look with all three types of @Autowired usage:
package com.springcore.autowireannotation;
import org.springframework.beans.factory.annotation.Autowired;
public Employee() {}
@Override
public String toString() {
return "Employee [name=" + name + ", address=" + address + "]";
}
}
1. Constructor Injection:
o Preferred for mandatory dependencies.
o Ensures that the dependency is always initialized at the time of object creation.
2. Setter Injection:
o Useful for optional dependencies or when you need to reconfigure
dependencies at runtime.
3. Field Injection:
o Simplest but harder to test and less flexible compared to other approaches.
For the Employee class, constructor injection is a good choice because the Address
dependency is likely mandatory for an Employee.
@Autowired
public Employee(Address address) {
this.address = address;
}
The @Qualifier annotation in Spring is used to resolve ambiguity when multiple beans of
the same type are available in the application context. It works in conjunction with
@Autowired to specify exactly which bean should be injected.
When there are multiple beans of the same type, Spring does not know which one to inject.
This results in a NoUniqueBeanDefinitionException. The @Qualifier annotation provides
a way to explicitly specify the bean to be injected.
Example
package com.springcore.autowireannotation;
import org.springframework.stereotype.Component;
@Component("homeAddress")
public class Address {
private String city = "New York";
private String state = "NY";
@Component("officeAddress")
public class Address {
private String city = "Los Angeles";
private String state = "CA";
In the Employee class, you can specify which Address bean to inject:
package com.springcore.autowireannotation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
@Component
public class Employee {
private String name = "John Doe";
@Autowired
@Qualifier("homeAddress") // Specify the exact bean to inject
private Address address;
If you're using an XML configuration instead of annotations, you can achieve the same result:
<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.xsd">
<bean id="homeAddress"
class="com.springcore.autowireannotation.Address">
<property name="city" value="New York"/>
<property name="state" value="NY"/>
</bean>
<bean id="officeAddress"
class="com.springcore.autowireannotation.Address">
<property name="city" value="Los Angeles"/>
<property name="state" value="CA"/>
</bean>
ApplicationContext context =
SpringApplication.run(AutowiredExampleApplication.class, args);
Output:
Advantages of @Qualifier
This ensures your application works as expected without ambiguity, even in complex
dependency injection scenarios.
Spring allows the configuration of collections (e.g., List, Set, Map, and Properties)
directly in the Spring configuration file. These are called "Standalone Collections" because
they can be defined as independent beans and injected into other beans.
1. List Example
XML Configuration
import java.util.List;
Main Application
Output
2. Set Example
XML Configuration
Bean Class
import java.util.Set;
Main Application
Output
3. Map Example
XML Configuration
Bean Class
import java.util.Map;
Main Application
4. Properties Example
XML Configuration
Bean Class
import java.util.Properties;
Main Application
Output
url = jdbc:mysql://localhost:3306/mydb
username = root
password = password
Standalone Collections as Dependencies
XML Configuration
Bean Class
Key Points
1. Type of Collections: Supported types include List, Set, Map, and Properties.
2. Reusability: Collections can be defined as standalone beans for reusability.
3. Dynamic Initialization: Allows dynamic configuration of collections in XML or
Java-based configurations.
This makes Spring highly flexible and powerful for managing collection-based dependencies.
Example
Here's the updated Java code and XML configuration file. The code now includes standalone
Map, Set, and LinkedList, and the XML configuration file is modified to reflect these
additions.
// Java Code
package com.springcore.standalone.collection;
import java.util.*;
return friends;
this.friends = friends;
return favoriteBooks;
this.favoriteBooks = favoriteBooks;
return addressMap;
}
public void setAddressMap(Map<String, String> addressMap) {
this.addressMap = addressMap;
return recentActivities;
this.recentActivities = recentActivities;
@Override
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd">
</beans>
Explanation:
2. XML Configuration:
o Defined util:set, util:map, and util:list for favoriteBooks,
addressMap, and recentActivities.
o Updated the Person bean to inject these collections using the appropriate
references.
You can now use this updated code and configuration to work with multiple standalone
collections in your Spring application.
Here’s an example of using the @Component annotation with a Student class in Spring.
import org.springframework.stereotype.Component;
@Component
public class Student {
private String name = "John Doe";
private int age = 20;
@Override
public String toString() {
return "Student [name=" + name + ", age=" + age + "]";
}
}
Configuration Class
package com.example;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan(basePackages = "com.example")
public class AppConfig {
}
import org.springframework.context.ApplicationContext;
import
org.springframework.context.annotation.AnnotationConfigApplicationContext;
Explanation
1. @Component: The Student class is annotated with @Component, which makes it a Spring-
managed bean.
2. @ComponentScan: In AppConfig, the @ComponentScan annotation ensures that Spring
scans the specified package (com.example) to find and register all @Component annotated
classes.
3. Application Context: The AnnotationConfigApplicationContext loads the
configuration and scans for components.
Output
When you run the MainApp class, you should see the following output:
This demonstrates how @Component simplifies bean declaration and enables Spring to
automatically manage the Student class as a bean.
Bean Scope