1 © Luxoft Training 2012 Spring Framework Inversion of control container.

Презентация:



Advertisements
Похожие презентации
1 © Luxoft Training 2012 Spring Framework Inversion of control container Part 2.
Advertisements

1 © Luxoft Training 2012 Spring Framework Inversion of control Part 1.
Evgeniy Krivosheev Andrey Stukalenko Vyacheslav Yakovenko Last update: Nov, 2013 Spring Framework Module 1 - Introduction.
Evgeniy Krivosheev Vyacheslav Yakovenko Last update: Feb, 2012 Spring Framework Module 4 – JNDI.
© Luxoft Training 2013 Annotations. © Luxoft Training 2013 Java reflection / RTTI // given the name of a class, get a "Class" object that // has all info.
1 © Luxoft Training 2012 Inner and anonymous classes.
Loader Design Options Linkage Editors Dynamic Linking Bootstrap Loaders.
Inner Classes. 2 Simple Uses of Inner Classes Inner classes are classes defined within other classes The class that includes the inner class is called.
© 2005 Cisco Systems, Inc. All rights reserved. BGP v Route Selection Using Policy Controls Applying Route-Maps as BGP Filters.
1 © Luxoft Training 2013 Spring Framework Module 10 JMS & EJB.
© 2005 Cisco Systems, Inc. All rights reserved. BGP v Customer-to-Provider Connectivity with BGP Connecting a Multihomed Customer to Multiple Service.
Unit II Constructor Cont… Destructor Default constructor.
Mobility Control and one-X Mobile. Mobility Control User Configuration Mobile Call Control requires PRI-U, BRI or SIP (RFC2833) trunks in the IP Office.
© 2002 IBM Corporation Confidential | Date | Other Information, if necessary © Wind River Systems, released under EPL 1.0. All logos are TM of their respective.
Operator Overloading Customised behaviour of operators Chapter: 08 Lecture: 26 & 27 Date:
© 2005 Cisco Systems, Inc. All rights reserved. BGP v Optimizing BGP Scalability Implementing BGP Peer Groups.
© 2009 Avaya Inc. All rights reserved.1 Chapter Two, Voic Pro Components Module Two – Actions, Variables & Conditions.
The waterfall model is a popular version of the systems development life cycle model for software engineering. Often considered the classic approach to.
1/27 Chapter 9: Template Functions And Template Classes.
The waterfall model is a popular version of the systems development life cycle model for software engineering. Often considered the classic approach to.
Транксрипт:

1 © Luxoft Training 2012 Spring Framework Inversion of control container

2 © Luxoft Training 2012 Spring Framework :: Introduction Spring is a lightweight, but at the same time flexible and universal framework used for creating Java SE and Java EE applications; Spring is a framework with an open source code; Spring is an application framework, not a layer framework; Spring includes several separate frameworks;

3 © Luxoft Training 2012 Spring Framework :: Introduction Rod Johnson created Spring in 2003; Spring took its rise from books Expert One-on-One Java J2EE Design and Development and J2EE Development Without EJB; The basic idea behind Spring is to simplify traditional approach to designing J2EE applications;

4 © Luxoft Training 2012

5 Spring Framework :: Framework Structure

6 © Luxoft Training 2012 Spring Framework :: Object dependencies Traditional approach PersonCompany class Person { public String name; public Company company; public Person() { String name = John Smith; Company company = new Company(); company.name = Luxoft; } class Company { public String name; }

7 © Luxoft Training 2012 Problems: o Class A directly depends on class B o Its impossible to test A separately from B o Lifetime of B object depends on A – its impossible to use B object in other places o Its not possible to replace B to another implementation AB Traditional approach Spring Framework :: Object dependencies

8 © Luxoft Training 2012 Approach with use of Singleton pattern SmithPersonLuxoftCompany class SmithPerson extends Person { public Person ivanovPerson = new Person(); public static Person create() { smithPerson.name = John Smith; smithPerson.company = LuxoftCompany.create(); return ivanovPerson; } class LuxoftCompany extends Company { public Company luxoftCompany = new Company(); public LuxoftCompany() { luxoftCompany = Luxoft; } public static Company create() { return luxoftCompany; } class Person { public String name; public Company company; } class Company { public String name; } Spring Framework :: Object dependencies

9 © Luxoft Training 2012 SmithPersonLuxoftCompany -Sepatate class specially for our task -Theres a direct link to LuxoftCompany in SmithPerson.create() -In case of transfer Smith to another company we have to change a code -Its impossible to temporally replace company for testing Approach with use of Singleton pattern Spring Framework :: Object dependencies

10 © Luxoft Training 2012 PersonCompany Inversion of Control Container approach <property name=companyReport" ref=companyReport"/> POJO – plain old Java Objectapplication-context.xml class Person { public String name; public Company company; } class Company { public String name; } class private CR companyReport; public void setCompanyReport() ; Spring Framework :: Object dependencies

11 © Luxoft Training 2012 PersonCompany Advantages: -Container creates necessary objects and manage its lifetime -Person and Company are not depended and not depend on any outer libraries -application-context documents the system and objects dependencies -Its very easy to make changes to object dependencies in the system Spring Framework :: Object dependencies Inversion of Control Container approach

12 © Luxoft Training 2012 AB AB JNDI repository Name B_NAME to look for B Register in JNDI under the B_NAME Traditional approach: dependencies inside the code Service Locator (JNDI в JEE) pattern: objects in the repository IoC: objects know nothing about each other AB Application context - Creates A object - Initialize - Creates A object -Initialize and inject B object dependency class A { private B b; } class B { } Spring Framework :: Object dependencies

13 © Luxoft Training 2012 Spring Framework :: IoC / DI Inversion of Control (IoC) pattern is the basis for Spring –Hollywood Principle – Don't call me, I'll call you (Could you recall any design pattern from GoF catalog to which this slogan can be applied? ); –Basic idea is to eliminate dependency of application components from certain implementation and to delegate IoC container rights to control classes instantiation; Martin Fowler suggested the name Dependency Injection (DI) because it better reflects the essence of the pattern (

14 © Luxoft Training 2012 Spring Framework :: IoC / DI Advantages of IoC containers: Dependency management and applying changes without recompiling; Facilitates reusing classes or components; Simplified unit testing; Cleaner code (classes dont initiate auxiliary objects); Its especially recommended to put those objects which implementation may change to the IoC container

15 © Luxoft Training 2012 Spring Framework :: IoC Containers BeanFactory is a central IoC container interface in Spring Framework (implementation used is XmlBeanFactory): –BeanFactory provides only basic low-level functionality; ApplicationContext is an interface enhancing BeanFactory and adding these features to the basic container features: –Simple integration with Spring AOP; –Work with resources and messages; –Event handling; –Support for internationalization; –Specific application contexts (for example, WebApplicationContext); It is Application Contexts that are used in a real life; BeanFactory could be used in exceptional cases, for example, if integrating Spring with a framework or when resources are critical and only IoC container is required.

16 © Luxoft Training 2012 Spring Framework :: IoC Containers There are several available implementations of ApplicationContext. Most widely used are: – GenericXmlApplicationContext (since v.3.0); – ClassPathXmlApplicationContext ; – FileSystemXmlApplicationContext ; – WebApplicationContext ; XML is a traditional way to configure container, though there are some other ways to configure metadata (annotations, Java code, etc.); In most cases it is easier and faster to use annotation-based configuration. However, you have to remember that annotation-based configuration has some restrictions and introduces additional code-level dependencies; Generally, user (developer) wont have to initiate Spring IoC container on his or her own;

17 © Luxoft Training 2012 Spring Framework :: Working with IoC Container In general, work of Spring IoC container can be represented as follows: When instantiating and initiating container, your application classes are combined with metadata (container configuration) and at the output you get fully configured and ready-to-work application.

18 © Luxoft Training 2012 Spring Framework :: Working with IoC Container Container creation: public void main(String args[]) { ApplicationContext context = new ClassPathXmlApplicationContext(application-context.xml"); BankApplication bankApplication = context.getBean(bankApplication); } ApplicationContext context = new ClassPathXmlApplicationContext( new String[] {"services.xml", "daos.xml"});

19 © Luxoft Training 2012 Spring Framework :: Working with IoC Container Configuration example: <beans xmlns=" xmlns:xsi=" xsi:schemaLocation="

20 © Luxoft Training 2012 Spring Framework :: Bean creation With the use of constructor: <bean id=clientService" class="ru.luxoft.training.samples.ClientService" /> With the use of a factory method: <bean id="clientService" class="ru.luxoft.training.samples.ClientService" factory-method="createInstance" /> class ClientService { public static ClientService createInstance() { ClientService cs = new ClientService(); // possibly perform some other operations // with cs instance return cs; }

21 © Luxoft Training 2012 With the use of not static factory method: <bean id="serviceFactory" class="examples.DefaultServiceFactory" /> <bean id="clientService" factory-bean="serviceFactory" factory-method="createClientServiceInstance" /> class DefaultServiceFactory { public ClientService createClientServiceInstance() { ClientService cs = new ClientService(); // possibly perform some other operations // with cs instance return cs; } Spring Framework :: Bean creation

22 © Luxoft Training 2012 Spring Framework :: Lazy initialization Lazy initialization is used to postpone bean creation to the time its first adressed. Lazy initialization of single bean: <bean id=lazy" class=ru.luxoft.training.ClientService" lazy-init=true" /> Lazy initialization of all beans in a container: … If singleton bean depends on lazy bean, lazy bean will be created in the moment of singleton bean creation.

23 © Luxoft Training 2012 Repeating

24 © Luxoft Training 2012 Spring Framework :: Context import Its often convinient to break context to several files:

25 © Luxoft Training 2012 Spring Framework :: Use of property files with context <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <bean id="dataSource" destroy-method="close" class="org.apache.commons.dbcp.BasicDataSource"> jdbc.driverClassName=org.hsqldb.jdbcDriver jdbc.url=jdbc:hsqldb:hsql://production:9002 jdbc.username=sa jdbc.password=root jdbc.properties:

26 © Luxoft Training 2012 Spring Framework :: Use of alias In this case bean named originalName may be referred to as aliasName; Used to provide future bean specialization. For example, we may refer beans as serviceCompany and itCompany, but for a while we have no special implementation for it, we use aliases:

27 © Luxoft Training 2012 Spring Framework :: Constructor DI Dependency injection with use of constructor public class ConstructorInjection { private Dependency dep; private String descr; public ConstructorInjection(Dependency dep, String descr) { this.dep = dep; this.descr = descr; }

28 © Luxoft Training 2012 Spring Framework :: Constructor DI Cyclic dependency: We will get BeanCurrentlyInCreationException duting DI Solution: to replace Constructor DI to Setter DI in one or both classes

29 © Luxoft Training 2012 Spring Framework :: Setter DI public class SetterInjection { private Dependency dep; private String descr; public void setDep(Dependency dep) { this.dep = dep; } public void setDescr(String descr) { this.descr = descr; }

30 © Luxoft Training 2012 Spring Framework :: Autowiring Example: service class to get user info UserDirectory LDAPUserDirectory DatabaseUserDirectory MockUserDirectory class LoginManager { UserDirectory userDirectory; } class UserDirectorySearch { UserDirectory userDirectory; } class UserInfo { UserDirectory userDirectory; } Let we have classes which need the information about the user <bean id=userDirectorySearch class=UserDirectorySearch>

31 © Luxoft Training 2012 Spring Framework :: Autowiring Now lets turn on the autowiring class LoginManager { UserDirectory userDirectory; } class UserDirectorySearch { UserDirectory userDirectory; } class UserInfo { LDAPUserDirectory ldapUserDirectory; } userDirectory property is initialized automatically:

32 © Luxoft Training 2012 Spring Framework :: Autowiring Spring is able to autowire (add dependencies) beans instead of ; In some cases it can significantly reduce the volume of configuration required; Can cause configuration to keep itself up to date as your object model evolve (for example, if you need to add an additional dependency, that dependency can be satisfied automatically); Autowiring by type can only work if there is exactly one bean of a property type; Harder for reading and checking dependencies than explicit wiring; Specified with autowire attribute in bean definition <bean id="..." class="..." autowire=no|byName|byType|constructor" />

33 © Luxoft Training 2012 Spring Framework :: Autowiring Autowiring modes: –no: no autowiring at all. This is the default; –byName: autowiring by property name. This option will inspect the container and look for a bean with ID exactly the same as the property which needs to be autowired. If such a bean cannot be found, the object is not autowired; –byType: autowiring by type. Works only if there is exactly one bean of property type in container. If there is more than one, then UnsatisfiedDependencyException is thrown; –constructor: container looks for a bean (or beans) of the constructor argument type. If there is more than one bean type or more than one, then UnsatisfiedDependencyException is thrown;

34 © Luxoft Training 2012 Spring Framework :: Annotation-based Configuration Spring container may be configured with the help of annotations; Basic supported annotations: For annotation-based configuration you should indicate in configuration of Spring container the following:

35 © Luxoft Training 2012 Spring Framework :: Annotation-based Applies to bean property setter method; Indicates that the affected bean property must be populated at configuration time (either through configuration or through autowiring); If the affected bean property has not been populated the container will throw an exception. This allows to avoid unexpected NullPointerException in system operation; public class SimpleMovieLister { private MovieFinder public void setMovieFinder(MovieFinder movieFinder) { this.movieFinder = movieFinder; }

36 © Luxoft Training 2012 Spring Framework :: Annotation-based Applied to: –Setter methods; –Constructors; –Methods with multiple arguments; –Properties (including private ones); –Arrays and typed collections (ALL beans of relevant class are autowired) Can be used this is the case, a bean with relevant ID is autowired; By default, if there is no matching bean, an exception is thrown. This behavior can be changed

37 © Luxoft Training 2012 Spring Framework :: Annotation-based Used for specifying Spring components without XML configuration Applies to classes Serves as a generic stereotype for every Spring-managed component It is recommended to use more specific stereotypes*: Generally, if you not sure which stereotype shall be used, To automatically register beans through annotations, specify the following command in container configuration:

38 © Luxoft Training 2012 Example of components use: package public class Adder { public int add(int a, int b) { return a + b; } package public class Calculator private Adder adder; public void makeAnOperation() { int r1 = adder.add(1,2); System.out.println("r1 = " + r1); } Spring Framework :: Annotation-based Configuration application_context.xml:

39 © Luxoft Training 2012 Repeating

40 © Luxoft Training 2012 Spring Framework :: Bean Scopes Bean Scopes General: Bean Scopes –Singleton –Prototype Web-specific: –Request –Session –Global session

41 © Luxoft Training 2012 Spring Framework :: Bean Scopes Singleton –By default –Single bean instance in container

42 © Luxoft Training 2012 Spring Framework :: Bean Scopes Prototype –A brand new bean instance is created every time it is injected into another bean or it is requested via getBean().

43 © Luxoft Training 2012 Spring Framework :: Bean Lifecycle

44 © Luxoft Training 2012 Spring Framework :: Bean Lifecycle Managing bean by implementing Spring interfaces Creating –Implement interface InitializingBean –Override method afterPropertiesSet() Deleting –Implement interface DisposableBean –Override method destroy()

45 © Luxoft Training 2012 Spring Framework :: Bean Lifecycle Managing bean via code without dependence on Spring: Add methods for initialization and/or deletion in a specific bean and indicate them in bean declaration: <bean id=example class=Example init-method=init" destroy-method=cleanup /> Methods for creating and/or deleting can be defined for all beans inside the container: <beans default-init-method=init default-destroy-method=cleanup>

46 © Luxoft Training 2012 Spring Framework :: Additional Features of ApplicationContext To access context (for example, for event publishing) a bean has to only implement interface ApplicationContextAware public class CommandManager implements ApplicationContextAware { private ApplicationContext applicationContext; public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; }

47 © Luxoft Training 2012 Spring Framework :: Events Receiving of the standard events: public class MyBean implements ApplicationListener { public void onApplicationEvent(ApplicationEvent event) { … } Publishing of the custom events: public class CustomEvent extends ApplicationEvent { public CustomEvent (Object obj) { super(obj); } context.publishEvent(new CustomEvent(new Object()));

48 © Luxoft Training 2012 Spring Framework :: Events Event processing in ApplicationContext is provided by: –ApplicationEvent class –ApplicationListener interface When an event happens all the beans which are registered in the container and implementing ApplicationListener interface are get notified ApplicationEvent – major implementations: –ContextRefreshedEvents – creating and refreshing of ApplicationContext Singletons are created ApplicationContext is ready to use –ContextClosedEvent After use of close() method –RequestHandledEvent For web applications only

49 © Luxoft Training 2012 Spring Framework :: Events Example: new employee registration. Possible event recipients: - informing security guards to do a pass - guards are subscribing the event - additionally there could be other subscribers, like HR or accounts department Task: save employee into database Solution: create a class which will add employee to database, and subsribe it to the event Advantages: - There could be any number of subscribers; - The system complexity does not depend on amount and type of subsribers - Adding subsriber does not adds the dependency: only himself knows about the subscriber (or separate subsribe mechanism) Disadvantages: - Sometimes may lead to the implicit application behavior

50 © Luxoft Training 2012 public class EmployeeRegistrationEvent extends ApplicationEvent { private Employee employee; public Employee getEmployee() { return employee; } public EmployeeRegitrationEvent (Employee emp) { this.employee = emp; } class EmployeeService implements ApplicationContextAware { private ApplicationContext context; public void setApplicationContext(ApplicationContext context) { this.context = context; } public void registerEmployee(String name, Date birthdate) { Employee empployee = new Employee(name, birthdate); context.publishEvent(new EmployeeRegitrationEvent(employee); } Spring Framework :: Events

51 © Luxoft Training 2012 public class WriteEmployeeToDB implements ApplicationListener private DB db; public void onApplicationEvent(EmployeeRegitrationEvent event) { db.save(event.getEmployee()); System.out.println("employee "+event.getEmployee().getName()+ " is saved in database"); } Spring Framework :: Events Task: save employee into database

52 © Luxoft Training 2012 Repeating

53 © Luxoft Training 2012 Spring Framework :: Localization messages_en_US.properties customer.name=Ivan Ivanov, age : {0}, URL : {1} messages_ru_RU.properties customer.name=Иван Иванов, возраст : {0}, URL : {1} <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource"> locale\customer\messages Folder to place the files: resources\locale\customer\ Locale.xml:

54 © Luxoft Training 2012 messages_en_US.properties customer.name=Ivan Ivanov, age : {0}, URL : {1} messages_ru_RU.properties customer.name=Иван Иванов, возраст : {0}, URL : {1} public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("locale.xml"); String name = context.getMessage("customer.name", new Object[] { 28, " }, Locale.US); System.out.println("Customer name (English) : " + name); String nameRussian = context.getMessage("customer.name", new Object[] {28, " }, Locale.RU); System.out.println("Customer name (Russian) : " + nameRussian); } Spring Framework :: Localization

55 © Luxoft Training 2012 Spring Framework :: Collections initialization public class Customer { private List list; private Set set; private Map map; private Properties props; } 1

56 © Luxoft Training Spring Framework :: Collections initialization public class Customer { private List list; private Set set; private Map map; private Properties props; }

57 © Luxoft Training 2012 Spring Framework :: Collections initialization public class Customer { private List list; private Set set; private Map map; private Properties props; }

58 © Luxoft Training 2012 Spring Framework :: Collections initialization The same as: CustomerBean customerBean = context.getBean(customerBean); customerBean.getMap().put("Key 1", new Integer(1)); customerBean.getMap().put("Key 2", context.getBean("personBean)); Person p = new Person(); p.setName("Ivan"); p.setAddress("address"); p.setAge(28); customerBean.getMap().put("Key 3", p);

59 © Luxoft Training Spring Framework :: Collections initialization public class Customer { private List list; private Set set; private Map map; private Properties props; }

60 © Luxoft Training 2012 <bean id="inheritedTestBean" abstract="true" class="org.springframework.beans.TestBean"> <bean id="inheritsWithDifferentClass" class="org.springframework.beans.DerivedTestBean" parent="inheritedTestBean" init-method="initialize"> Spring Framework :: Properties inheritance

61 © Luxoft Training child.admin s= Applicable to properties, list, set, map. Spring Framework :: Merge of collections

62 © Luxoft Training 2012 Spring Framework :: Emply and null properties

63 © Luxoft Training 2012 <beans xmlns=" xmlns:p=" <bean name="p-namespace" class="com.example.ExampleBean" /> <bean name="john-modern" class="com.example.Person" p:name="John Doe" p:spouse-ref="jane" /> Spring Framework :: p-namespace

64 © Luxoft Training 2012 Spring Framework :: Configuration profiles GenericXmlApplicationContext ctx = new GenericXmlApplicationContext(); ctx.getEnvironment().setActiveProfiles("dev"); ctx.load("classpath:/com/bank/config/xml/*-config.xml"); ctx.refresh(); Setting profile and configuration loading in the Java code: -Dspring.profiles.active="profile1,profile2" Setting profile in the command line parameters:

65 © Luxoft Training 2012 Spring Framework :: public class TransferServiceConfig DataSource public TransferService transferService() { return new DefaultTransferService(accountRepository(), feePolicy()); public AccountRepository accountRepository() { return new JdbcAccountRepository(dataSource); public FeePolicy feePolicy() { return new ZeroFeePolicy(); } AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); ctx.getEnvironment().setActiveProfiles("dev"); // find and register classes within ctx.scan("com.bank.config.code"); ctx.refresh();

66 © Luxoft public class Application MessageService mockMessageService() { return new MessageService() { public String getMessage() { return "Hello World!"; } }; } public static void main(String[] args) { ApplicationContext context = new AnnotationConfigApplicationContext(Application.class); MessagePrinter printer = context.getBean(MessagePrinter.class); printer.printMessage(); } Spring Framework :: Java-based configuration Example from the latest Spring Quick Start:

67 © Luxoft Training 2012 public interface MessageService { String getMessage(); public class MessagePrinter private MessageService service; public void printMessage() { System.out.println(this.service.getMessage()); } Spring Framework :: Java-based configuration Example from the latest Spring Quick Start:

68 © Luxoft Training 2012 Spring Framework :: Maven configuration org.springframework spring-context RELEASE Example from the latest Spring Quick Start:

69 © Luxoft Training 2012 Repeating

70 © Luxoft Training 2012 Exercises Developing of simple Spring application