Basic Hello World Implementation
Create a simple POJO class with a string property:
public class Greeting {
private String message;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
@Override
public String toString() {
return "Greeting{message='" + message + "'}";
}
}
Configure the Spring bean in XML configuration:
<?xml version="1.0" encoding="UTF-8"?>
<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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="greeting" class="com.example.pojo.Greeting">
<property name="message" value="Spring Framework"/>
</bean>
</beans>
Test the configuartion with a unit test:
public class SpringTest {
@Test
public void testGreetingBean() {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
Greeting greeting = (Greeting) context.getBean("greeting");
System.out.println(greeting.toString());
}
}
Dependency Injection Example
Define a data access interface:
public interface CustomerRepository {
void fetchCustomers();
}
Implement the interface with different data sources:
public class DefaultCustomerRepository implements CustomerRepository {
@Override
public void fetchCustomers() {
System.out.println("Fetching customers from default repository");
}
}
public class DatabaseCustomerRepository implements CustomerRepository {
@Override
public void fetchCustomers() {
System.out.println("Fetching customers from database");
}
}
Create a service that depends on the repository:
public interface CustomerService {
void retrieveCustomers();
}
public class CustomerServiceImpl implements CustomerService {
private CustomerRepository repository;
public void setRepository(CustomerRepository repository) {
this.repository = repository;
}
@Override
public void retrieveCustomers() {
repository.fetchCustomers();
}
}
Configure dependency injection in Spring 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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="databaseRepo" class="com.example.repository.DatabaseCustomerRepository"/>
<bean id="defaultRepo" class="com.example.repository.DefaultCustomerRepository"/>
<bean id="customerService" class="com.example.service.CustomerServiceImpl">
<property name="repository" ref="defaultRepo"/>
</bean>
</beans>
Test the service with dependency injection:
public class CustomerServiceTest {
@Test
public void testCustomerRetrieval() {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
CustomerService service = (CustomerService) context.getBean("customerService");
service.retrieveCustomers();
}
}