Sei sulla pagina 1di 15

Spring 3 Dependency Injection using Annotation

An alternative to XML setups is provided by annotation-based configuration. In other words,


instead of using XML to describe a bean wiring, the developer moves the configuration into the
component class itself by using annotations on the relevant class, method, or field declaration

Expected duration: 120 minutes (excluding homework)

Lab Exercises

Exercise 1: Service class configured with XML (30 minutes)

Exercise 2: Service class configured with annotation (30 minutes)

Exercise 3: XML based configuration (30 minutes)

Exercise 4: Java based configuration (30 minutes)

Homework Exercise

Exercise 0: Import projects of this lab


1. Create a new "Java Working Set"

2. Import all projects under "samples" directory of this lab

return to the top

Exercise 1: Service class configured with XML (non-annotation based)


Learning points:

This is provided to show the difference between XML based configuration versus
annotation based configuration which you will do in the next exercise. In this
exercise, you are going to configure your beans by declaring them in the XML
configuration file, beans.xml. In the next exercise, you are going to declare them
using @Service and @Repository annotations.

Tasks to be performed:
1.

Build and run "di_xml_Service" project

2.

Study the project

(1.1) Build and run "di_xml_Service" project

Hello, Spring Student

(1.2) Study the project


1. beans.xml
<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"
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.xsd">
<bean id = "customerDao"
class = "com.softwarecampus.examples.dao.CustomerDaoImpl">
</bean>
<bean id = "customerService"
class = "com.softwarecampus.examples.services.CustomerServiceImpl">
<property name="customerDao" ref="customerDao"></property>
</bean>
</beans>
2. CustomerDao.java and CustomerDaoImpl.java
package com.softwarecampus.examples.dao;
public interface CustomerDao {
public String getCustomerName();
}

package com.softwarecampus.examples.dao;
public class CustomerDaoImpl implements CustomerDao {

public String getCustomerName() {


// For the sake of simplicity, return hard-coded custome rname
return "customer name";
}

3. CustomerService.java and CustomerServiceImpl.java


package com.softwarecampus.examples.services;
public interface CustomerService {
public String getCustomerGreeting();
}

package com.softwarecampus.examples.services;

import com.softwarecampus.examples.dao.CustomerDao;
public class CustomerServiceImpl implements CustomerService {
CustomerDao customerDao;
public void setCustomerDao(CustomerDao customerDao) {
this.customerDao = customerDao;
}
public String getCustomerGreeting() {
String greeting = "Hello, " + customerDao.getCustomerName();
return greeting;
}
}
4. Main.java
package com.softwarecampus.examples;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.softwarecampus.examples.services.CustomerService;
public class Main {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext(
new String[] { "beans.xml" });
CustomerService customerService =
(CustomerService) context.getBean("customerService");
System.out.println(customerService.getCustomerGreeting());
}

Exercise 2: Service class configured with annotation

Learning points:

You can configure Service class with @Service annotation and Dao/Repository
classes with @Repository annotation

Tasks to be perfgormed:
1.

Build and run "di_Service_Annotation" project

2.

Study the project

3.

Modify the project (for your own exercise)

(2.1) Build and run "di_Service_Annotation" project

Hello, Spring Student

(2.2) Study the project


1. beans.xml.
<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"
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.xsd">
<context:component-scan base-package="com.softwarecampus.examples" />
<!-<context:component-scan base-package="com.softwarecampus.examples" >
<context:include-filter type="regex"
expression="com.softwarecampus.examples.dao.*Dao.*" />
<context:exclude-filter type="regex"
expression="com.softwarecampus.examples.dao.*.*" />
<context:exclude-filter type="annotation"
expression="org.springframework.stereotype.Service" />
</context:component-scan>
-->
</beans>
2. CustomerDaoImpl.java
package com.softwarecampus.examples.dao;
import org.springframework.stereotype.Repository;
//
//
//
//
//

A class that is annotated with "@Repository" is eligible for


Spring org.springframework.dao.DataAccessException translation.
The annotated class is also clarified as to its role in the
overall application architecture for the purpose of tools,
aspects, etc.

// As of Spring 2.5, this annotation also serves as a specialization


// of @Component, allowing for implementation classes to be autodetected
// through classpath scanning.
@Repository("customerDao")
public class CustomerDaoImpl implements CustomerDao {
public String getCustomerName() {
// For the sake of simplicity, return hard-coded custome rname
return "Spring Student";

3. CustomerServiceImpl.java
package com.softwarecampus.examples.services;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.softwarecampus.examples.dao.CustomerDao;
@Service("customerService")
public class CustomerServiceImpl implements CustomerService {
@Autowired
CustomerDao customerDao;
public String getCustomerGreeting() {
String greeting = "Hello, " + customerDao.getCustomerName();
return greeting;
}
}
4. Main.java
package com.softwarecampus.examples;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.softwarecampus.examples.services.CustomerService;
public class Main {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext(
new String[] { "beans.xml" });
CustomerService customerService =
(CustomerService) context.getBean("customerService");
System.out.println(customerService.getCustomerGreeting());
}
}

(2.3) Modify the project (for your own exercise)


1. Add another set of Dao interface and implementation classes as following.
package com.softwarecampus.examples.dao;
public interface CourseDao {
public String getCourseName();
}

package com.softwarecampus.examples.dao;
import org.springframework.stereotype.Repository;
@Repository("courseDao")
public class CourseDaoImpl implements CourseDao {

public String getCourseName() {


// For the sake of simplicity, return hard-coded course name
return "Spring projgramming";
}

2. Modify the application so that the result of running the application displays the following.
Hello, Spring Student, Your are taking Spring Programming!

Exercise 3: Configuration file in XML


Learning points:

Typically Spring configuration is through XML configuration file. In the next


exercise, you are going to modify this using Java-based configuration.

Tasks to be perfgormed:
1. Build and run "di_Configuration_XML" project
2. Study the project

(3.1) Build and run "di_Configuration_XML" project

accountRepository.findById("A123").getBalance()
accountRepository.findById("C456").getBalance()
Transfering 100 dollars from A123 to C456
accountRepository.findById("A123").getBalance()
accountRepository.findById("C456").getBalance()

= 1000.0
= 0.0
= 900.0
= 100.0

(3.2) Study the project


1. beans.xml
<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"
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.xsd">
<bean id = "accountRepository"
class = "com.softwarecampus.examples.account.repository.InMemoryAccountRepository">

</bean>
<bean id = "transferService"
class = "com.softwarecampus.examples.account.service.TransferServiceImpl">
<constructor-arg name="accountRepository" ref="accountRepository"/>
</bean>
</beans>
2. Main.java
package com.softwarecampus.examples.account;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.softwarecampus.examples.account.domain.Account;
import com.softwarecampus.examples.account.repository.AccountRepository;
import com.softwarecampus.examples.account.service.TransferService;
public class Main {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext(
new String[] { "beans.xml" });
// retrieve the beans we'll use during testing
AccountRepository accountRepository = (AccountRepository)
context.getBean("accountRepository");
TransferService transferService = (TransferService)
context.getBean("transferService");
// create accounts to test against
accountRepository.add(new Account("A123", 1000.00));
accountRepository.add(new Account("C456", 0.00));
System.out.println("accountRepository.findById(\"A123\").getBalance() = " +
accountRepository.findById("A123").getBalance());
System.out.println("accountRepository.findById(\"C456\").getBalance() = " +
accountRepository.findById("C456").getBalance());
// check account balances before transfer
assertThat(accountRepository.findById("A123").getBalance(), equalTo(1000.00));
assertThat(accountRepository.findById("C456").getBalance(), equalTo(0.00));
// perform transfer
System.out.println("Transfering 100 dollars from A123 to C456 ");
transferService.transfer(100.00, "A123", "C456");
System.out.println("accountRepository.findById(\"A123\").getBalance() = " +
accountRepository.findById("A123").getBalance());
System.out.println("accountRepository.findById(\"C456\").getBalance() = " +
accountRepository.findById("C456").getBalance());
// check account balances after transfer
assertThat(accountRepository.findById("A123").getBalance(), equalTo(900.00));
assertThat(accountRepository.findById("C456").getBalance(), equalTo(100.00));
}

Exercise 4: Java-based Configuration


Learning points:

Annotating a class with the @Configuration indicates that the class can be used by
the Spring IoC container as a source of bean definitions.

Tasks to be perfgormed:
1. Build and run "di_Configuration_Java" project
2. Study the project

(4.1) Build and run "di_Configuration_Java" project

accountRepository.findById("A123").getBalance()
accountRepository.findById("C456").getBalance()
Transfering 100 dollars from A123 to C456
accountRepository.findById("A123").getBalance()
accountRepository.findById("C456").getBalance()

= 1000.0
= 0.0
= 900.0
= 100.0

(4.2) Study the project


1. AppConfig.java
package com.softwarecampus.examples.account;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import
import
import
import

com.softwarecampus.examples.account.repository.AccountRepository;
com.softwarecampus.examples.account.repository.InMemoryAccountRepository;
com.softwarecampus.examples.account.service.TransferService;
com.softwarecampus.examples.account.service.TransferServiceImpl;

@Configuration
public class AppConfig {
@Bean
public TransferService transferService() {
return new TransferServiceImpl(accountRepository());
}
@Bean
public AccountRepository accountRepository() {
return new InMemoryAccountRepository();
}
}

2. Main.java
package com.softwarecampus.examples.account;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import com.softwarecampus.examples.account.domain.Account;
import com.softwarecampus.examples.account.repository.AccountRepository;
import com.softwarecampus.examples.account.service.TransferService;
public class Main {
public static void main(String[] args) {
// Create a new AnnotationConfigApplicationContext, deriving bean
// definitions from the given annotated classes and automatically
// refreshing the context. Note that we don't use a context
// configuration file in this example.
ApplicationContext ctx = new
AnnotationConfigApplicationContext(AppConfig.class);
// retrieve the beans we'll use during testing
AccountRepository accountRepository = ctx.getBean(AccountRepository.class);
TransferService transferService = ctx.getBean(TransferService.class);
// create accounts to test against
accountRepository.add(new Account("A123", 1000.00));
accountRepository.add(new Account("C456", 0.00));
System.out.println("accountRepository.findById(\"A123\").getBalance() = " +
accountRepository.findById("A123").getBalance());
System.out.println("accountRepository.findById(\"C456\").getBalance() = " +
accountRepository.findById("C456").getBalance());
// check account balances before transfer
assertThat(accountRepository.findById("A123").getBalance(), equalTo(1000.00));
assertThat(accountRepository.findById("C456").getBalance(), equalTo(0.00));
// perform transfer
System.out.println("Transfering 100 dollars from A123 to C456 ");
transferService.transfer(100.00, "A123", "C456");
System.out.println("accountRepository.findById(\"A123\").getBalance() = " +
accountRepository.findById("A123").getBalance());
System.out.println("accountRepository.findById(\"C456\").getBalance() = " +
accountRepository.findById("C456").getBalance());
// check account balances after transfer
assertThat(accountRepository.findById("A123").getBalance(), equalTo(900.00));
assertThat(accountRepository.findById("C456").getBalance(), equalTo(100.00));
}

Homework Exercise
1. The homework is to modify the di_basics_InjectRef project in the basics to use Java-based
configuration.

Potrebbero piacerti anche