Introduction to Spring Framework

A presentation at Muffin Conference Sofia in October 2014 in Sofia, Bulgaria by Petyo Dimitrov

Slide 1

Slide 1

Introduction to Spring Framework Petyo Dimitrov

Slide 2

Slide 2

Agenda • Purpose and history of the framework • Spring modules • Spring core 1. beans 2. lifecycle 3. dependency injection • Spring Data • Spring MVC Introduction to Spring Framework 2/57

Slide 3

Slide 3

What is Spring? An Enterprise Java Developer’s life Introduction to Spring Framework 3/57

Slide 4

Slide 4

What is Spring (continued) “Spring is amongst (if not the most) popular application development frameworks for enterprise Java™. Many developers use Spring to create high performing, easily testable, reusable code without any lock-in.” SpringSource Introduction to Spring Framework 4/57

Slide 5

Slide 5

History • first version was created by Rod Johnson and released in 2004 • version 2.0 – 2006 • Java 1.3, AspectJ и JPA • version 3.0 – 2009 • Java5, annotations, SpEL, JavaConfig, REST • version 4.0 – 2013 • Java 8, Groovy 2, JavaEE7 support • current version is 4.1.0 GA (by September 2014) Introduction to Spring Framework 5/57

Slide 6

Slide 6

Origin – enterprise applications client layer present ation business logic database • layers are composed of components • every component contains part of the application’s logic • components aim for: 1. 2. Introduction to Spring Framework high cohesion loose coupling 6/57

Slide 7

Slide 7

Origin – EJB (1) import java.rmi.RemoteException; import javax.ejb.EJBObject; public interface HelloWorld extends EJBObject { public String sayHello() throws RemoteException; } import java.rmi.RemoteException; import java.ejb.CreateException; import javax.ejb.EJBHome; public interface HelloWorldHome extends EJBHome { public HelloWorld create() throws CreateException, RemoteException; } Introduction to Spring Framework 7/57

Slide 8

Slide 8

Origin – EJB (2) import javax.ejb.SessionBean; import javax.ejb.SessionContext; public class HelloWorldBean implements SessionBean { protected SessionContext ctx; public String sayHello() { return “Hello, world !”; } public void setSessionContext(SessionContext ctx) { this.ctx = ctx; } public void ejbCreate() {} public void ejbRemove() {} public void ejbActivate() {} public void ejbPassivate() {} } Introduction to Spring Framework 8/57

Slide 9

Slide 9

Origin – EJB (3) <ejb-jar> <description>HelloWorld deployment desc</description> <display-name>HelloWorld</display-name> <enterprise-beans> <session> <display-name>HelloWorld</display-name> <ejb-name>HelloWorld</ejb-name> <home>HelloWorldHome</home> <remote>HelloWorld</remote> <ejb-class>HelloWorldBean</ejb-class> <session-type>Stateless</session-type> <transaction-type>Container</transaction-type> </session> </enterprise-beans> … <ejb-jar> Introduction to Spring Framework 9/57

Slide 10

Slide 10

Alternative implementation with Spring (1) public interface HelloWorld { public String sayHello() } public class HelloWorldBean implements HelloWorld { private String name; public void setName(String name) {this.name = name;} public String sayHello() {return “Hello, ” + name;} } <beans …> <bean id=”hello” class=”HelloWorldBean”> <property name=”name” value=”colleagues”/> </bean> </beans> Introduction to Spring Framework 10/57

Slide 11

Slide 11

Alternative implementation with Spring (2) • standalone application example: ApplicationContext context = new ClassPathXmlApplicationContext(“config.xml”); HelloWorld bean = context.getBean(“hello”, HelloWorld.class); bean.sayHello(); Introduction to Spring Framework 11/57

Slide 12

Slide 12

Purposes of Spring • simplify working with Java EE technologies • encourage good practices for software development • ease performing common tasks • allow the developer to focus on the business problem at hand Introduction to Spring Framework 12/57

Slide 13

Slide 13

Spring Framework • • • • open source framework unobtrusive (relies on POJOs) modular integrated with other frameworks • de facto standard for developing enterprise Java applications Introduction to Spring Framework 13/57

Slide 14

Slide 14

Spring modules http://spring.io/projects Introduction to Spring Framework 14/57

Slide 15

Slide 15

Spring Core • IoC container and beans: 1. backbone of the framework 2. allows defining components (beans) with specific lifecycle 3. allows using DI • Context – mean for accessing beans (and other resources) in a unified manner (similar to JNDI) Introduction to Spring Framework 15/57

Slide 16

Slide 16

Bean lifecycle Introduction to Spring Framework 16/57

Slide 17

Slide 17

Bean instantiation Introduction to Spring Framework 17/57

Slide 18

Slide 18

Bean instantiation (1) • via constructor: class MovieFinderImpl implements MovieFinder { public MovieFinderImpl() {} } <bean id=”finder” class=”MovieFinderImpl”/> Introduction to Spring Framework 18/57

Slide 19

Slide 19

Bean instantiation (2) • via static factory method class MovieFinderImpl implements MovieFinder { private MovieFinderImpl() {} public static MovieFinder createInstance() { return new MovieFinderImpl(); } } <bean id=”finder” class=”MovieFinderImpl” factory-method=”createInstance” /> Introduction to Spring Framework 19/57

Slide 20

Slide 20

Populate bean properties Introduction to Spring Framework 20/57

Slide 21

Slide 21

Inversion of Control • pattern for developing applications • a.k.a. “don’t call me, I’ll call you” • types: 1. 2. 3. 4. 5. Factory pattern, Template Method pattern, Strategy pattern, Dependency Injection, etc. Introduction to Spring Framework 21/57

Slide 22

Slide 22

Dependency Injection (1) class MovieService { private MovieFinder finder; public MovieService() { finder = new MovieFinderImpl(); } } Introduction to Spring Framework 22/57

Slide 23

Slide 23

Dependency Injection (2) class MovieService { private MovieFinder finder; private Context ctx = …; public MovieService() { finder=(MovieFinder)ctx.lookup(“id”); } } … ctx.rebind(“id”, new MovieFinderImpl()) Introduction to Spring Framework 23/57

Slide 24

Slide 24

Dependency Injection (3) class MovieService { private MovieFinder finder; public MovieService(MovieFinder f){ finder = f; } // or public setMovieFinder(MovieFinder f) { finder = f; } } Introduction to Spring Framework 24/57

Slide 25

Slide 25

Същност на Dependency Injection • DI is a type of IoC • DI is a pattern allowing components to define their dependencies, so that the container can inject the service in the dependent object (i.e. client) • basic types of DI: 1. via constructor (for mandatory dependencies) 2. via setter method Introduction to Spring Framework 25/57

Slide 26

Slide 26

Dependency Injection – Spring example <bean id=”service” class=”MovieService”> <constructor-arg ref=”finder”/> </bean> // or <bean id=”service” class=”MovieService”> <property name=”finder” ref=”finder”/> </bean> Introduction to Spring Framework 26/57

Slide 27

Slide 27

Dependency Injection advantages • reduces the amount of code • simplifies unit testing a component • encourages writing logic complying with the interface • ensures loose coupling between components • supports eager and lazy loading • provides control over the bean’s lifecycle Introduction to Spring Framework 27/57

Slide 28

Slide 28

Spring-aware interfaces Introduction to Spring Framework 28/57

Slide 29

Slide 29

Spring-aware interfaces – example • BeanNameAware • BeanFactoryAware • ApplicationContextAware class MovieFinderImpl implements MovieFinder, BeanNameAware { public void setBeanName(String name) { … } } Introduction to Spring Framework 29/57

Slide 30

Slide 30

Bean initialization Introduction to Spring Framework 30/57

Slide 31

Slide 31

Bean initialization - example <bean id=”b1” class=”Bean1”/> public class Bean1 { @PostConstruct public void initialize() {} } <bean id=”b2” class=”Bean2”/> public class Bean2 implements InitializingBean { public void afterPropertiesSet() {} } <bean id=”b3” class=”Bean3” init-method=”init”/> public class Bean3 { public void init() {} } Introduction to Spring Framework 31/57

Slide 32

Slide 32

Bean destruction Introduction to Spring Framework 32/57

Slide 33

Slide 33

Bean destruction – example <bean id=”b1” class=”Bean1”/> public class Bean1 { @PreDestroy public void destroy() {} } <bean id=”b2” class=”Bean2”/> public class Bean2 implements DisposableBean { public void destroy() {} } <bean id=”b3” class=”Bean3” destroy-method=”clean”/ public class Bean3 { public void clean() {} } Introduction to Spring Framework 33/57

Slide 34

Slide 34

Bean scopes • basic 1. singleton 2. prototype 3. custom • for web applications: 1. request - new instance for every HTTP query 2. session – new instances for every HTTP session 3. global session – for portlets Introduction to Spring Framework 34/57

Slide 35

Slide 35

Bean scope – singleton <bean id=”finderBean” class=”MovieFinderImpl”> <bean id=”app1” class=”MovieService”> <property name=”finder” ref=”finderBean”/> </bean> <bean id=”app2” class=”MovieService”> <property name=”finder” ref=”finderBean”/> </bean> • single instances of finderBean • must not keep state (unless synced) • better performance Introduction to Spring Framework 35/57

Slide 36

Slide 36

Bean scope – prototype <bean id=”finderBean” class=”MovieFinderImpl” scope=”prototype”> <bean id=”app1” class=”MovieService”> <property name=”finder” ref=”finderBean”/> </bean> <bean id=”app2” class=”MovieService”> <property name=”finder” ref=”finderBean”/> </bean> • two instances of finderBean • may keep state • worse performances Introduction to Spring Framework 36/57

Slide 37

Slide 37

Annotations • reduce the need of XML • store configuration information in the code (+/-) • used for: 1. 2. 3. 4. linking beans (and literals) defining beans(type, scope, etc.) registering in babies tune transaction demarcation • and many more projects (e.g. MVC) Introduction to Spring Framework 37/57

Slide 38

Slide 38

Example XML configuration class MovieService { private MovieFinder finder; public setMovieFinder(MovieFinder f) { finder = f; } } <bean id=”finder” class=”MovieFinderImpl”/> <bean id=”service” class=”MovieService”> <property name=”finder” ref=”finder”/> </bean> Introduction to Spring Framework 38/57

Slide 39

Slide 39

Automatic wiring • via @Autowired (+ reflection) • specifics: + removes the need for configuration + simplifies working with a bean - not as precise as explicit searching (might need @Qualifier) • implementation: 1. via field name 2. via field type 3. via constructor Introduction to Spring Framework 39/57

Slide 40

Slide 40

Automatic wiring – example class MovieService { @Autowired private MovieFinder finder; } <context:annotation-config /> <bean id=”finder” class=”MovieFinderImpl”/> <bean id=”service” class=” MovieService” /> Introduction to Spring Framework 40/57

Slide 41

Slide 41

Automatic wiring – example • via Spring типове: 1. @Component – base stereotype 2. @Service – for business logic 3. @Repository – for accessing data bases (*) 4. @Controller – for Spring MVC 5. @Configuration – for Java configuration • @Scope – 3 types of basic scopes • simplifies marking the different layers of the application Introduction to Spring Framework 41/57

Slide 42

Slide 42

Automatic wiring – example @Service class MovieService { @Autowired private MovieFinder finder; } <context:component-scan base-package= “com.musala” /> <context:annotation-config /> Introduction to Spring Framework 42/57

Slide 43

Slide 43

Configuration • options (via games): 1. XML– for infrastructure beans and backward compatibility 2. Annotations – for standard beans 3. JavaConfig – for further reduce in XML config. @Configuration @ComponentScan(“com.musala”) class TestConfiguration { @Bean public MovieFinder finder() { return new MovieFinderImpl(); } } Introduction to Spring Framework 43/57

Slide 44

Slide 44

Spring Data • JDBC support: 1. DataSource – provides and manages connections to the database 2. JDBCTemplate – helper class simplifying JDBC usage in Spring: jdbcTemplate.queryForInt(“select count(*) from movie”) • ORM support: 1. Hibernate – direct integration 2. JPA – using a JPA persistence provider (e.g. Hibernate) Introduction to Spring Framework 44/57

Slide 45

Slide 45

JPA integration (1) @Bean public EntityManagerFactory entityManagerFactory() throws SQLException { HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); vendorAdapter.setGenerateDdl(false); LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean(); factory.setDataSource(dataSource()); factory.setPackagesToScan(“com.musala.domain”); factory.setJpaVendorAdapter(vendorAdapter); factory.afterPropertiesSet(); return factory.getObject(); } Introduction to Spring Framework 45/57

Slide 46

Slide 46

JPA integration (2) @Bean public DataSource dataSource() throws SQLException { EmbeddedDatabaseBuilder b = new EmbeddedDatabaseBuilder(); b.addScript(“sql/schema.ddl”); return b.setType(EmbeddedDatabaseType.H2).build(); } @Bean public EntityManager entityManager(EntityManagerFactory entityManagerFactory) { return entityManagerFactory.createEntityManager(); } Introduction to Spring Framework 46/57

Slide 47

Slide 47

JPA integration (3) @Repository @Transactional public class MovieServiceImpl implements MovieService { @PersistenceContext private EntityManager em; @Transactional(readOnly=true) public List<Movie> findAll() { List<Movie> m = em.createNamedQuery(“findAllMovies”, Movie.class).getResultList(); return m; } } Introduction to Spring Framework 47/57

Slide 48

Slide 48

JPA Repository abstraction (1) • wraps the EntityManager and provides a simple interface for database operations public interface CrudRepository<T,ID> extends Repository<T, ID> { T save(T entity); T findOne(ID id); boolean exists(ID id); Iterable<T> findAll(); long count(); void delete(ID id); void delete(T entity); void delete(Iterable<? extends T> entities); void deleteAll(); } Introduction to Spring Framework 48/57

Slide 49

Slide 49

JPA Repository abstraction (2) • no need to implement the basic CRUD methods • custom methods following the naming convention, allow the framework to deduce their queries • only methods with non-standard logic and noncompliant with the naming convention must be implemented public interface MovieRepository extends CrudRepository<Movie, Long> { public List<Movie> findByTitle(String title); public List<Movie> findByTitleAndReleaseDate(String title, Date releaseDate); } Introduction to Spring Framework 49/57

Slide 50

Slide 50

Model-View-Controller basics ❶ user sends a request to a specific URL ❷ controller calls the model and receives data ❸ controller associates the model and view and passes the control to the view ❹ view uses the model and generates a representation ❺ users receives the representation sent as response Introduction to Spring Framework 50/57

Slide 51

Slide 51

Spring MVC • model-view-controller framework • uses DispatcherServlet in order to direct queries to their handler • handlers can be tweaked via @Controller and @RequestMapping • dynamic view selection, changing locale and visual theme • allows creation of RESTful web services Introduction to Spring Framework 51/57

Slide 52

Slide 52

Spring MVC workflow Introduction to Spring Framework 52/57

Slide 53

Slide 53

Controller – example @Controller @RequestMapping(“/movies”) public class MovieController { @Autowired private MovieService movieService; @Autowired private ConversionService conversionService; … @RequestMapping(value = “/{id}”, method = RequestMethod.GET) @ResponseBody public MovieView getById(@PathVariable String id) { return conversionService.convert(movieService.getById(id), MovieView.class); } @RequestMapping(value = { “/”, “” }, method = RequestMethod.POST) @ResponseBody public MovieView create(@Valid @RequestBody MovieCreateForm f){ return conversionService.convert(movieService.create(f), MovieView.class); } } Introduction to Spring Framework 53/57

Slide 54

Slide 54

Converter – example • allows converting fields (bean fields) and complete beans @Component public class MovieSearchViewConverter implements Converter<Movie, MovieSearchView> { @Override public MovieSearchView convert(Movie movie) { return new MovieSearchView(movie.getId(), movie.getTitle(), movie.getReleaseDate()); } } Introduction to Spring Framework 54/57

Slide 55

Slide 55

Validation – example • declarative validation of input data • standard JSR-303 annotations or custom implementation (hibernate) public class MovieCreateForm { @Size(min = 3, max = 100) @NotEmpty private String title;

  • @Valid @NotNull private Date releaseDate; } Introduction to Spring Framework 55/57

Slide 56

Slide 56

Demo Въведение в Spring Framework 56/57

Slide 57

Slide 57

petyo.dimitrov @musala.com Introduction to Spring Framework 57/57