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

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



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

© 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.
1 © Luxoft Training 2013 Spring Framework Module 10 JMS & EJB.
© Luxoft Training 2013 Using Reflection API in Java.
Copyright 2003 CCNA 4 Chapter 11 Scaling IP Addresses By Your Name.
© 2005 Cisco Systems, Inc. All rights reserved. BGP v Route Selection Using Policy Controls Using Multihomed BGP Networks.
© 2006 Cisco Systems, Inc. All rights reserved. SND v Configuring a Cisco IOS Firewall Configuring a Cisco IOS Firewall with the Cisco SDM Wizard.
1/27 Chapter 9: Template Functions And Template Classes.
Evgeniy Krivosheev Vyacheslav Yakovenko Last update: Feb, 2012 Spring Framework Module 4 – JNDI.
Operator Overloading Customised behaviour of operators Chapter: 08 Lecture: 26 & 27 Date:
© 2005 Cisco Systems, Inc. All rights reserved. BGP v Route Selection Using Policy Controls Applying Route-Maps as BGP Filters.
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.
© 2002 IBM Corporation Confidential | Date | Other Information, if necessary © Wind River Systems, released under EPL 1.0. All logos are TM of their respective.
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.
2005 Pearson Education, Inc. All rights reserved. 1 Object-Oriented Programming: Interface.
Unit II Constructor Cont… Destructor Default constructor.
© 2005 Cisco Systems, Inc. All rights reserved. BGP v Customer-to-Provider Connectivity with BGP Connecting a Multihomed Customer to Multiple Service.
© 2009 Avaya Inc. All rights reserved.1 Chapter Three, Voic Pro Advanced Functions Module Four – Voic Campaigns.
Транксрипт:

1 © Luxoft Training 2012 Spring Framework Inversion of control container Part 2

2 © 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:

3 © 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; }

4 © 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

5 © 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:

6 © 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:

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

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

9 © 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().

10 © Luxoft Training 2012 Spring Framework :: Bean Lifecycle

11 © 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()

12 © 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>

13 © 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; }

14 © 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()));

15 © 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

16 © 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

17 © 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

18 © 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

19 © 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:

20 © 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

21 © 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:

22 © 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();

23 © 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:

24 © 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:

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

26 © Luxoft Training 2012 Bank Application Please work on exercise 16