Скачать презентацию
Идет загрузка презентации. Пожалуйста, подождите
Презентация была опубликована 9 лет назад пользователемФилипп Астахов
1 1 © Luxoft Training 2012 Spring Framework Inversion of control container Part 2
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 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 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 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 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 7 © Luxoft Training 2012 Spring Framework :: Bean Scopes Bean Scopes General: Bean Scopes –Singleton –Prototype Web-specific: –Request –Session –Global session
8 8 © Luxoft Training 2012 Spring Framework :: Bean Scopes Singleton –By default –Single bean instance in container
9 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 10 © Luxoft Training 2012 Spring Framework :: Bean Lifecycle
11 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
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:
13 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 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 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 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 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 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
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}
20 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 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 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 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 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 25 © Luxoft Training 2012 Spring Framework :: Maven configuration org.springframework spring-context RELEASE Example from the latest Spring Quick Start:
26 26 © Luxoft Training 2012 Bank Application Please work on exercise 16
Еще похожие презентации в нашем архиве:
© 2024 MyShared Inc.
All rights reserved.