Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Spring_Core Technologies_rus

Spring_Core Technologies_rus

Alexander Akoemov

March 22, 2016
Tweet

More Decks by Alexander Akoemov

Other Decks in Technology

Transcript

  1. Core Container March 2016, Spring Core Technologies Talk, Alexander Akoemov

    3 Core Container состоит : - Core – базовые классы для фреймворка - Bean – BeanFactory имплементация шаблона factory. - Context – строит базовую структуру на основе Core и Beans, интерфейс ApplicationContext один из основных в модуле. - Expression Language – для запросов и изменения объектов при выполнении
  2. IoC Containers March 2016, Spring Core Technologies Talk, Alexander Akoemov

    4 Spring IoC Containers - основа Spring Framework. Контейнер создаст объекты, свяжет их вместе, настроит их, и управляет их жизненным циклом от создания до разрушения. IoC использует инъекции зависимостей (DI) для управления компонентами, которые составляют приложения. Такие объекты называются Spring Beans. Контейнер получает свои инструкции для создания экземпляров объектов, настройки и сборки за счет чтения конфигурации. Виды конфигурации : • XML • Java аннотации • Java код • Groovy.
  3. IoC Containers Types March 2016, Spring Core Technologies Talk, Alexander

    Akoemov 5 1) Spring BeanFactory Container - Это самая простая реализация контейнера, базовая поддержка DI и определяется org.springframework.beans.factory.BeanFactory интерфейсом. BeanFactory и связанный интерфейсов, таких как BeanFactoryAware, InitializingBean, DisposableBean 2) Spring ApplicationContext Container - Этот контейнер добавляет больше enterprise функций, такие как способность обрабатывать property файл. Этот контейнер определяется org.springframework.context.ApplicationContext интерфейсом. Контейнер ApplicationContext включает в себя все функциональные возможности контейнера BeanFactory.
  4. BeanFactory Container March 2016, Spring Core Technologies Talk, Alexander Akoemov

    6 public class HelloWorld { private String message; public void setMessage(String message) { this.message = message; } public void getMessage() { System.out.println("Your Message : " + message); } } public class MainApp { public static void main(String[] args) { XmlBeanFactory factory = new XmlBeanFactory( new ClassPathResource("Beans.xml")); HelloWorld obj = (HelloWorld) factory.getBean("helloWorld"); obj.getMessage(); } }
  5. ApplicationContext Container March 2016, Spring Core Technologies Talk, Alexander Akoemov

    7 import org.springframework.context.ApplicationContext; import org.springframework.context.support.FileSystemXmlApplicationContext; public class MainApp { public static void main(String[] args) { ApplicationContext context = new FileSystemXmlApplicationContext("C:/src/Beans.xml"); HelloWorld obj = (HelloWorld) context.getBean("helloWorld"); obj.getMessage(); } }
  6. Dependency Injection(DI) March 2016, Spring Core Technologies Talk, Alexander Akoemov

    8 • Constructor-based dependency injection public class ConstructorTypeDIBean { private ServiceBean serviceBean; // constructor to inject the dependency public ConstructorTypeDIBean(ServiceBean serviceBean) { this.serviceBean = serviceBean; } public void useService() { System.out.println("ConstructorTypeDIBean:" + erviceBean.action()); } }
  7. Dependency Injection(DI) March 2016, Spring Core Technologies Talk, Alexander Akoemov

    9 • Setter-based dependency injection public class SetterTypeDIBean { private ServiceBean serviceBean; // a setter method to inject the dependency. public void setServiceBean(ServiceBean serviceBean) { this.serviceBean = serviceBean; } public void useService() { System.out.println("SetterTypeDIBean:" + serviceBean.action()); } }
  8. Bean Definition March 2016, Spring Core Technologies Talk, Alexander Akoemov

    10 Properties Description class This attribute is mandatory and specify the bean class to be used to create the bean. name This attribute specifies the bean identifier uniquely. In XML-based configuration metadata, you use the id and/or name attributes to specify the bean identifier(s). scope This attribute specifies the scope of the objects created from a particular bean definition and it will be discussed in bean scopes chapter. constructor-arg This is used to inject the dependencies and will be discussed in next chapters. properties This is used to inject the dependencies and will be discussed in next chapters. autowiring mode This is used to inject the dependencies and will be discussed in next chapters. lazy-initialization mode A lazy-initialized bean tells the IoC container to create a bean instance when it is first requested, rather than at startup. initialization method A callback to be called just after all necessary properties on the bean have been set by the container. It will be discussed in bean life cycle chapter. destruction method A callback to be used when the container containing the bean is destroyed. It will be discussed in bean life cycle chapter.
  9. Bean Definition March 2016, Spring Core Technologies Talk, Alexander Akoemov

    11 <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <!-- A simple bean definition --> <bean id="..." class="..."> <!-- collaborators and configuration for this bean go here --> </bean> <!-- A bean definition with lazy init set on --> <bean id="..." class="..." lazy-init="true"> <!-- collaborators and configuration for this bean go here --> </bean> <!-- A bean definition with initialization method --> <bean id="..." class="..." init-method="..."> <!-- collaborators and configuration for this bean go here --> </bean> <!-- A bean definition with destruction method --> <bean id="..." class="..." destroy-method="..."> <!-- collaborators and configuration for this bean go here --> </bean> <!-- more bean definitions go here --> </beans>
  10. Java Based Configuration March 2016, Spring Core Technologies Talk, Alexander

    Akoemov 12 import org.springframework.context.annotation.*; @Configuration public class HelloWorldConfig { @Bean public HelloWorld helloWorld(){ return new HelloWorld(); } } HelloWorldConfig.java HelloWorld.java public class HelloWorld { private String message; public void setMessage(String message){ this.message = message; } public void getMessage(){ System.out.println("Your Message : " + message); } }
  11. Java Based Configuration March 2016, Spring Core Technologies Talk, Alexander

    Akoemov 13 MainApp.java import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.*; public class MainApp { public static void main(String[] args) { ApplicationContext ctx = new AnnotationConfigApplicationContext(HelloWorldConfig.class); HelloWorld helloWorld = ctx.getBean(HelloWorld.class); helloWorld.setMessage("Hello World!"); helloWorld.getMessage(); } }
  12. Bean Scopes March 2016, Spring Core Technologies Talk, Alexander Akoemov

    14 • singleton - This scopes the bean definition to a single instance per Spring IoC container (default). • prototype - This scopes a single bean definition to have any number of object instances. • request - This scopes a bean definition to an HTTP request. Only valid in the context of a web-aware Spring ApplicationContext. • session - This scopes a bean definition to an HTTP session. Only valid in the context of a web-aware Spring ApplicationContext. • global-session - This scopes a bean definition to a global HTTP session. Only valid in the context of a web-aware Spring ApplicationContext. <!-- A bean definition with singleton scope --> <bean id="..." class="..." scope="singleton"> <!-- collaborators and configuration for this bean go here --> </bean>
  13. Autowiring March 2016, Spring Core Technologies Talk, Alexander Akoemov 15

    no – по умолчанию byName - по имени property (setter). byType – по типу property (setter). constructor – по типу аргументов конструктора. autodetect – сначала по constructor’у , если не получиться по типу byType.
  14. Autowiring March 2016, Spring Core Technologies Talk, Alexander Akoemov 16

    import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; public class Profile { @Autowired @Qualifier("student1") private Student student; public Profile() { System.out.println("Inside Profile constructor."); } public void printAge() { System.out.println("Age : " + student.getAge()); } public void printName() { System.out.println("Name : " + student.getName()); } } @Autowired The @Autowired annotation can apply to bean property setter methods, non-setter methods, constructor and properties
  15. @Import Annotation March 2016, Spring Core Technologies Talk, Alexander Akoemov

    17 @Configuration @Import(ConfigA.class) public class ConfigB { @Bean public B b() { return new B(); } } @Configuration public class ConfigA { @Bean public A a() { return new A(); } } public static void main(String[]args){ ApplicationContext ctx = new AnnotationConfigApplicationContext(ConfigB.class); // now both beans A and B will be available... A a=ctx.getBean(A.class); B b=ctx.getBean(B.class); } класс ConfigA класс ConfigB ApplicationContext
  16. Bean Post Processors March 2016, Spring Core Technologies Talk, Alexander

    Akoemov 19 public class HelloWorld { private String message; public void setMessage(String message){ this.message = message; } public void getMessage(){ System.out.println("Your Message : " + message); } public void init(){ System.out.println("Bean is going through init."); } public void destroy(){ System.out.println("Bean will destroy now."); } }
  17. Bean Post Processors March 2016, Spring Core Technologies Talk, Alexander

    Akoemov 20 import org.springframework.beans.factory.config.BeanPostProcessor; import org.springframework.beans.BeansException; public class InitHelloWorld implements BeanPostProcessor { public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { System.out.println("BeforeInitialization : " + beanName); return bean; // you can return any other object as well } public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { System.out.println("AfterInitialization : " + beanName); return bean; // you can return any other object as well } } BeforeInitialization : helloWorld Bean is going through init. AfterInitialization : helloWorld Your Message : Hello World! Bean will destroy now.
  18. Sources and Resources March 2016, Spring Core Technologies Talk, Alexander

    Akoemov 21 http://docs.spring.io/spring/docs/current/spring-framework- reference/htmlsingle/#spring-core Pro Spring, 4th Edition Author: Chris Schaefer , Clarence Ho , Rob Harrop Примеры: https://github.com/akoemov/Spring_CoreTechnologies
  19. Questions are welcome! March 2016, Spring Core Technologies Talk, Alexander

    Akoemov 22 Alexander Akoemov email: [email protected] Linkedin: www.linkedin.com/in/akoemov GitHub: github.com/akoemov Skype: akoemov