Dependency Injection and Spring.ppt - Universitetet i Oslo · Dependency Injection with...

22
Dependency Injection and Spring Spring

Transcript of Dependency Injection and Spring.ppt - Universitetet i Oslo · Dependency Injection with...

Page 1: Dependency Injection and Spring.ppt - Universitetet i Oslo · Dependency Injection with SpringDependency Injection with Spring • Cf fConfiguration: How to instantiate, configure,

Dependency Injectionp y j

and

SpringSpring

Page 2: Dependency Injection and Spring.ppt - Universitetet i Oslo · Dependency Injection with SpringDependency Injection with Spring • Cf fConfiguration: How to instantiate, configure,

Problem areaProblem area

• Large information systems contains a huge number of classes that work togetherH t i th l t th ?• How to wire the classes together?

Page 3: Dependency Injection and Spring.ppt - Universitetet i Oslo · Dependency Injection with SpringDependency Injection with Spring • Cf fConfiguration: How to instantiate, configure,

Example: The StudentSystemExample: The StudentSystem

• To improve your skills in Java development, you decide to develop a student systemY d id t fil t t t d t i f ti• You decide to use a file to store student information

• You create a class FileStudentDAO responsible for writing and reading to the filewriting and reading to the file

• You create a class StudentSystem responsible for performing the logic of the systemperforming the logic of the system

• You’ve learned that it’s a good thing to program to interfacesinterfaces

Page 4: Dependency Injection and Spring.ppt - Universitetet i Oslo · Dependency Injection with SpringDependency Injection with Spring • Cf fConfiguration: How to instantiate, configure,

The StudentSystemResponsible for The StudentSystemperforming useful operations on

students

<< interface >>yer

StudentSystem

- int getNrOfStudents( String subjectCode )

DefaultStudentSystem<implements>

<depends>

Ser

vice

lay

<< interface >>St d tDAO

depends

<implements>e la

yer

StudentDAO

- Collection<Student> getAllStudents()

FileStudentDAOimplements

Per

sist

ence

Responsible for adding,deleting and gettingstudents from some

storage medium A file

Page 5: Dependency Injection and Spring.ppt - Universitetet i Oslo · Dependency Injection with SpringDependency Injection with Spring • Cf fConfiguration: How to instantiate, configure,

The DefaultStudentSystemThe DefaultStudentSystempublic class DefaultStudentSystem implements StudentSystempublic class DefaultStudentSystem implements StudentSystem{

private StudentDAO studentDAO = new FileStudentDAO();

public int getNrOfStudents( String subjectCode )public int getNrOfStudents( String subjectCode ){

Collection<Student> students = studentDAO.getAllStudents();

int count = 0;The StudentDAO

reference isint count = 0;

for ( Student student : students ){

if ( student getSubjects contains( subjectCode ) )

reference is instantiated with a

concrete class

if ( student.getSubjects.contains( subjectCode ) ){

count++;}

}}

return count;}

}}

Page 6: Dependency Injection and Spring.ppt - Universitetet i Oslo · Dependency Injection with SpringDependency Injection with Spring • Cf fConfiguration: How to instantiate, configure,

Works! Or ?Works! Or...?

• The system is a big success – University of Oslo wants to adopt it!

You usef

University of Oslo usesa MySQL database toa file to store the

student information

a MySQL database to store their student

information

Page 7: Dependency Injection and Spring.ppt - Universitetet i Oslo · Dependency Injection with SpringDependency Injection with Spring • Cf fConfiguration: How to instantiate, configure,

Works! Or ?Works! Or...?

• You make a new implementation of the StudentDAO for University of Oslo, a MySQLStudentDAO:

<<interface>>StudentDAO

<implements><implements>

FileStudentDAO MySQLStudentDAO

Page 8: Dependency Injection and Spring.ppt - Universitetet i Oslo · Dependency Injection with SpringDependency Injection with Spring • Cf fConfiguration: How to instantiate, configure,

Works! Or ?Works! Or...?

• Won’t work! The FileStudentDAO is hard-coded into the StudentSystem:

public class DefaultStudentSystem implements StudentSystem{

private StudentDAO studentDAO = new FileStudentDAO();...

• The DefaultStudentSystem implementation is responsible for obtaining a StudentDAOresponsible for obtaining a StudentDAO

• Dependent both on the StudentDAO interface and the implementationp

Page 9: Dependency Injection and Spring.ppt - Universitetet i Oslo · Dependency Injection with SpringDependency Injection with Spring • Cf fConfiguration: How to instantiate, configure,

Works! Or ?Works! Or...?

• How to deploy the StudentSystem at different locations?• Develop various versions for each location?

– Time consuming– Confusing and error-prone– Requires more efforts for versioning– Requires more efforts for versioning

• Use Dependency Injection!– More specific term derived from the term Inversion of ControlMore specific term derived from the term Inversion of Control

Page 10: Dependency Injection and Spring.ppt - Universitetet i Oslo · Dependency Injection with SpringDependency Injection with Spring • Cf fConfiguration: How to instantiate, configure,

Dependency InjectionDependency Injection

Traditional Using Dependency Injection

Interface/StudentDAO

Main class/DefaultStudentSystem

Interface/StudentDAO

Main class/DefaultStudentSystem

Implementation/Fil St d tDAO

Implementation/Fil St d tDAOFileStudentDAO FileStudentDAO

IoC Container(Spring)

Configurationmetadata

Page 11: Dependency Injection and Spring.ppt - Universitetet i Oslo · Dependency Injection with SpringDependency Injection with Spring • Cf fConfiguration: How to instantiate, configure,

Dependency InjectionDependency Injection

• Objects define their dependencies only through constructor arguments or setter-methodsD d i i j t d i t bj t b t i• Dependencies are injected into objects by a container (like Spring)

• Inversion of Control• Inversion of Control...• Two major types of dependency injection

Setter injection (preferred in Spring)– Setter injection (preferred in Spring)– Constructor injection

Page 12: Dependency Injection and Spring.ppt - Universitetet i Oslo · Dependency Injection with SpringDependency Injection with Spring • Cf fConfiguration: How to instantiate, configure,

Spring ConfigurationSpring Configuration

• Bean: A class that is managed by a Spring IoC container• Setter based DI: Provide a public set-method for the

d d f

public class DefaultStudentSystem implements StudentSystem{

dependency reference

{private StudentDAO studentDAO;

public void setStudentDAO( StudentDAO studentDAO ){

Spring uses the setterto inject the dependency

behind the scenes{this.studentDAO = studentDAO;

}

public int getNrOfStudents( String subjectCode )

behind the scenes

public int getNrOfStudents( String subjectCode ){

List students = studentDAO.getAllStudents();

// method logic goes here// method logic goes here...}

}

Page 13: Dependency Injection and Spring.ppt - Universitetet i Oslo · Dependency Injection with SpringDependency Injection with Spring • Cf fConfiguration: How to instantiate, configure,

Dependency Injection with SpringDependency Injection with Spring

C f f• Configuration: How to instantiate, configure, and assemble the objects in your application

• The Spring container accepts many configuration• The Spring container accepts many configuration formats

• XML based configuration most common, Java properties g , p por programmatically

<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN“ "http://www.springframework.org/dtd/spring-beans.dtd">

<beans>

<bean id=”studentDAO"class="no.uio.inf5750.impl.FileStudentDAO“/>

</beans>

Bean definition

Page 14: Dependency Injection and Spring.ppt - Universitetet i Oslo · Dependency Injection with SpringDependency Injection with Spring • Cf fConfiguration: How to instantiate, configure,

Dependency Injection with SpringDependency Injection with Spring

<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN“ "http://www.springframework.org/dtd/spring-beans.dtd">

<beans>

Bean identifier, must be unique

<beans>

<bean id=”studentDAO"class="no.uio.inf5750.impl.FileStudentDAO“/> Package-qualified class name,

normally the implementation class<bean id=”studentSystem"

class="no.uio.inf5750.impl.DefaultStudentSystem"><property name=”studentDAO”>

<ref bean=”studentDAO"/>

normally the implementation class

Refers to the studentStore<ref bean= studentDAO /></property>

</bean>

</beans>

Refers to the studentStoreattribute in the Java class

</beans>Refers to the

studentStore beanStudentStoreinjected into

StudentRegister!

Page 15: Dependency Injection and Spring.ppt - Universitetet i Oslo · Dependency Injection with SpringDependency Injection with Spring • Cf fConfiguration: How to instantiate, configure,

Dependency Injection with SpringDependency Injection with Spring

<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN“ "http://www.springframework.org/dtd/spring-beans.dtd">

<beans>

Change to use the MySQL implementation <beans>

<bean id=”studentDAO"class="no.uio.inf5750.impl.MySQLStudentDAO“/>

instead of the File implementation

<bean id=”studentSystem"class="no.uio.inf5750.impl.DefaultStudentSystem"><property name=”studentDAO”>

<ref bean=”studentDAO"/><ref bean= studentDAO /></property>

</bean>

</beans> University of Oslo can now use</beans> University of Oslo can now usethe system by altering one configuration line without

changing the compiled code!

Page 16: Dependency Injection and Spring.ppt - Universitetet i Oslo · Dependency Injection with SpringDependency Injection with Spring • Cf fConfiguration: How to instantiate, configure,

Dependency InjectionDependency Injection

• Advantages of Dependency Injection– Easier to swap implementations of dependencies

The system can be re configured without changing the compiled– The system can be re-configured without changing the compiled code

– Easier testing– Improved re-usability of your classes– Cleaner code

Page 17: Dependency Injection and Spring.ppt - Universitetet i Oslo · Dependency Injection with SpringDependency Injection with Spring • Cf fConfiguration: How to instantiate, configure,

Bean propertiesBean properties

• Bean properties can be values defined inline as well (not only references to other beans)S i ’ XML b d fi ti t• Spring’s XML-based configuration supports– Straight values (primitives, Strings...)– Collections (Lists Sets Maps)– Collections (Lists, Sets, Maps)– Properties

Page 18: Dependency Injection and Spring.ppt - Universitetet i Oslo · Dependency Injection with SpringDependency Injection with Spring • Cf fConfiguration: How to instantiate, configure,

Example: Straight valuesExample: Straight valuespublic class DefaultStudentSystem

implements StudentSystem{

private int maxNrOfStudentsPerCourse;

bli id M N OfS d P C ( i )

Java bean

public void setMaxNrOfStudentsPerCourse( int nr ){

this.maxNrOfStudentsPerCourse = nr;}

<bean id=”studentSystem” Spring XMLbean id studentSystemclass=”no.uio.inf5750.impl.DefaultStudentSystem”><property name=”maxNrOfStudentsPerCourse”>

<value>100</value></property>

Spring XMLconfiguration file

(beans.xml)/property

</bean>

Page 19: Dependency Injection and Spring.ppt - Universitetet i Oslo · Dependency Injection with SpringDependency Injection with Spring • Cf fConfiguration: How to instantiate, configure,

Example: Collectionspublic class DefaultStudentSystem

Example: Collectionsimplements StudentSystem

{private Map subjects;

bli id S bj ( M bj )

Java bean

public void setSubjects( Map subjects ){

this.subjects = subjects;}

Spring XML

<bean id=”studentSystem”class=”no.uio.inf5750.impl.DefaultStudentSystem”><property name=”subjects”> Spring XML

configuration file(beans.xml)

<property name= subjects ><entry>

<key><value>INF5750</value></key><value>Open Source Software Development</value>

</entry></entry><entry>

<key><value>INF5760</value></key><value>Health Information Systems</value>

</entry></entry></property>

</bean>

Page 20: Dependency Injection and Spring.ppt - Universitetet i Oslo · Dependency Injection with SpringDependency Injection with Spring • Cf fConfiguration: How to instantiate, configure,

SummarySummarypublic class DefaultStudentSystem

implements StudentSystemClass where dependencies

implements StudentSystem{

private StudentDAO studentDAO;

public void setStudentDAO( StudentDAO studentDAO )

are being injected

{this.studentDAO = studentDAO;

}

Configuration

Fil St d tDAO

The implementationto inject

<bean id=”studentDAO"class="no.uio.inf5750.impl.FileStudentDAO“/>

b id ” d S "

FileStudentDAO

IoC Container(Spring)

<bean id=”studentSystem"class="no.uio.inf5750.impl.DefaultStudentSystem"><property name=”studentDAO”>

<ref bean=”studentDAO"/></property>p p y

</bean>

Page 21: Dependency Injection and Spring.ppt - Universitetet i Oslo · Dependency Injection with SpringDependency Injection with Spring • Cf fConfiguration: How to instantiate, configure,

IoC using AnnotationsIoC using Annotations

• Annotation is a meta-tag – applied to classes, methods... – Associated with program behaviour

@C t• @Component– Defines a class as a Spring container managed component

• @Autowired• @Autowired– Tells Spring to inject a component

• Classpath scanning for components• Classpath scanning for components– <context:component-scan base-package="org.example"/>

Page 22: Dependency Injection and Spring.ppt - Universitetet i Oslo · Dependency Injection with SpringDependency Injection with Spring • Cf fConfiguration: How to instantiate, configure,

ResourcesResources

• Lots of books on Spring– Rod Johnson, Juergen Hoeller: Expert One-on-One J2EE

Development without EJBDevelopment without EJB– Justin Gehtland, Bruce A. Tate: Better, Faster, Lighter Java– Craig Walls and Ryan Breidenbach: Spring in Action

• The Spring reference documentation– www.springframework.org