is Introduction to Spring 5 and JPA 2

Size: px
Start display at page:

Download "is Introduction to Spring 5 and JPA 2"

Transcription

1 or tri N s di IO n tio AT uc od pr re U ed AL riz ho ut na EV U is i ib d tie PY oh pr O n C io t bu Introduction to Spring 5 and JPA 2

2 This material is copyrighted by LearningPatterns Inc. This content and shall not be reproduced, edited, or distributed, in hard copy or soft copy format, without express written consent of LearningPatterns Inc. Copyright LearningPatterns Inc. For more information about Java Enterprise Java, or related courseware, please contact us. Our courses are available globally for license, customization and/or purchase. LearningPatterns. Inc. Global Courseware Services Main St. Ste Fishkill NY, USA voice and fax Java, and all Java-based trademarks and logo trademarks are registered trademarks of Oracle, Inc., in the United States and other countries. LearningPatterns and its logos are trademarks of LearningPatterns Inc. All other products referenced herein are trademarks of their respective holders.

3 Table of Contents Introduction to Spring 5 and JPA Introduction to Spring 5 and Spring MVC/REST 1 Workshop Overview 2 Workshop Objectives: Spring Capabilities 3 Workshop Objectives: JPA Capabilities 4 Workshop Agenda 5 Typographic Conventions 6 Labs 7 8 Lesson Objectives 9 Overview 10 Spring and Enterprise Applications 11 The Spring Modules 12 The Spring Distribution 13 The Spring jars 14 A Word About JUnit 15 JUnit Example 16 Lab 1.1: Setting Up the Environment 17 Spring Introduction 18 Managing Beans: Core Spring Capability 19 A Basic Spring Application 20 The JavaTunes Online Store 21 Some JavaTunes Types 22 XML Configuration Example 23 The Spring Container 24 Instantiating and Using the Container 25 Why Bother - What do we Gain? 26 Summary: Working With Spring 27 More on ApplicationContext 28 Some BeanFactory/ApplicationContext API 29 Mini-Lab: Review Javadoc 30 Lab 1.2: Hello Spring World 31 Annotation-Based Configuration Example 32 A Brief Note on Annotations 33 Enabling Annotations / Detecting Beans 34 Spring's XML Schemas 35 Lab 1.3: Spring Annotations 36 Dependency Injection 37 Dependencies Between Objects 38 Example of a Direct Dependency 39 Dependency Inversion 40 Dependency Injection (DI) in Spring 41 Injection with Autowired (JSR-330) Example 43 Dependency Injection Reduces Coupling 44 Advantages of Dependency Injection 45 Constructor Injection 46 Setter Injection vs. Constructor Injection 47 Copyright LearningPatterns Inc. All rights reserved i

4 Qualifying Injection by Name 48 Lab 1.4: Dependency Injection 49 Review Questions 50 Lesson Summary 51 Lesson Summary 52 Session 2: Configuration in Depth 53 Lesson Objectives 54 Java-based Configuration 55 Java Configuration Overview 56 Using Java-based Configuration 57 Dependency Injection 58 How Does it Work? 59 Dependencies in Configuration Classes 60 Injecting Configuration Classes 61 Capabiliites 62 Mini-Lab: Review Javadoc 63 Integrating Configuration Types 64 XML Pro / Con 65 Java-based Configuration: Pro / Con 66 Choosing a Configuration Style 67 Integrating Configuration 69 <import>: XML by XML 70 Importing Between XML/@Configuration 71 Scanning Classes 72 Lab Options 73 Lab 2.1: Java-based Configuration 74 Bean Scope and Lifecycle 75 Bean Scope 76 Specifying Bean Scope - XML 77 to Specify Bean Scope 78 Bean Creation/Destruction Lifecycle 79 [Optional] Bean Creation Lifecycle Details 80 [Optional] BeanPostProcessor 81 [Optional] Event Handling 82 Lab 2.2: Bean Lifecycle 83 Externalizing Properties 84 Externalizing Values in Properties Files 85 Accessing Externalized Properties 86 The Spring Environment 87 SpEL: Spring Expression Language Overview 88 Additional SpEL Examples 89 Mini-Lab: Review SpEL Reference 90 Profiles 91 Profile Overview 92 The First Configuration 93 Defining Second Configuration 94 Using the Configurations 95 Declaring Profiles 96 Enabling Profiles 97 Profiles - XML Configuration 98 Profiles in JUnit tests 99 Copyright LearningPatterns Inc. All rights reserved ii

5 Lab 2.3: Profiles 100 Review Questions 101 Lesson Summary 102 Lesson Summary 103 Session 3: Introduction to Spring Boot 104 Lesson Objectives 105 maven Overview 106 About Maven 107 How We'll Work With Maven 108 Core Maven Concepts 109 The POM (Project Object Model) 110 POM - Required Elements 111 POM - External Dependencies 112 Common Maven Artifacts for Spring 113 Repositories 114 Maven Project Structure 115 Executing maven Goals 116 Spring Boot Overview 117 Motivation for Spring Boot 118 Spring Boot Project 119 Goals for Spring Boot Project 120 How is Spring Boot Structured? 121 Dependency Management with Spring Boot 122 Equivalent POM without Spring Boot 123 Configuration with Spring Boot 124 Programming with Spring Boot 125 Getting Started 126 Mini-Lab: Review Boot Reference 127 Mini-Lab: Spring Boot - Starter Projects 128 Spring Boot Hello World 129 Our Goals for Hello World 130 POM for Hello World 131 spring-boot-starter-parent 132 spring-boot-starter-parent POM Excerpt 133 spring-boot-dependencies POM Excerpt 134 spring-boot-starter 135 spring-boot-starter POM Excerpt 136 Summary 137 Mini-Lab: Spring Boot - Brief Review of POMs 138 Hello World Overview 139 Hello World Code 140 Output of HelloBootWorld 141 How it Works 142 Easy Configuration with Properties 143 Executable Jar Packaging 144 Lab 1.1: Hello Boot World 145 Recap of what we've seen 146 Session 4: Spring Testing 147 Lesson Objectives 148 Testing and JUnit Overview 149 Testing Overview 150 JUnit Overview 151 Copyright LearningPatterns Inc. All rights reserved iii

6 Writing a Test First Example 152 Running Tests in the IDE 153 Running Tests in Other Environments 154 Naming Conventions and Organizing Tests 155 Positive and Negative Tests 156 Writing Test Methods 157 Assertions 158 Test 159 Test Fixtures Example 160 Test 161 Order of Execution 162 [Optional] Lab 4.1: Using JUnit 163 Spring TestContext Framework 164 Spring TestContext Overview 165 Common TestContext Types 166 Using Spring's TestContext 167 Context Management / Caching 168 Using Spring Boot Test 169 Under the Hood 170 Lab 4.2: Using Spring Testing 171 Session 5: Introduction to the Java Persistence API (JPA) 172 Lesson Objectives 173 JPA Overview 174 The Issues with Persistence Layers 175 Object-Relational Mapping (ORM) Issues 176 Java Persistence API (JPA) Overview 177 JPA Benefits 178 Java Persistence Environments 179 JPA Architecture High Level View 180 JPA Architecture Programming View 181 Using JPA 182 Mapping a Simple Class 183 Entity Classes 184 Entity Class Requirements 185 Event: An Example Entity Class 186 javax.persistence.entity Annotation 187 The Event Class 188 javax.persistence.id and id property 189 Field Access or Property Access 190 The EVENTS Table 191 Generated Id 192 Sequences 193 Mini-Lab: Review Javadoc 194 Mapping Properties 195 Basic Mapping Types 196 How Do You Persist to the DB? 197 Lab 5.1: Mapping an Entity Class 198 Persistence Unit and Entity Manager 199 The Persistence Unit 200 persistence.xml 201 Classes included in a persistence unit 202 The EntityManager (EM) & Persistence Context 203 EntityManager Interface 204 Copyright LearningPatterns Inc. All rights reserved iv

7 Obtaining an Entity Manager 205 Java SE Environments 206 Entity Manger and Transactions 207 Using JPA in Java SE 208 Retrieving Persistent Objects 209 Mini-Lab: Review Javadoc 210 Lab 5.2: Using an Entity Class 211 More About Mappings 212 Default Mappings Annotations 214 Field and Property Access 215 Temporal (Date/Time) Mappings 216 Java 8 Date/Time Support Overview 217 Date and Time Classes Overview 218 JPA Support for Java 8 Date/Time 219 Mapping Enums 220 Lab 5.3: Refining the Mapping 221 Logging 222 Logging Overview 223 hibernate.show_sql 224 Logging Overview 225 Spring Boot Logging Configuration 226 JPA Logging with Spring Boot 227 Hibernate Logging Categories 228 Lab 5.4: Controlling Logging 229 Review Questions 230 Lesson Summary 231 Lesson Summary 232 Session 6: Spring / JPA Integration 233 Lesson Objectives 234 Overview 235 Data Access Support 236 Datasources 237 Example: Configuring a DataSource 238 Example: JNDI Lookup of a DataSource 239 Properties Files 240 XML vs Java Config vs Properties Files 241 Using Spring with JPA 242 Spring Support for JPA 243 Managing the EntityManager[Factory] JEE: Obtaining an EMF From JNDI LocalContainerEntityManagerFactoryBean 246 Spring/JPA Integration Configuration 247 Example: XML Configuration LocalEntityManagerFactoryBean 250 JPA Repository 251 Extended Persistence Context 252 Lab 6.1: Integrating Spring and JPA 253 Review Questions 254 Lesson Summary 255 Session 7: JPA Updates and Queries 256 Copyright LearningPatterns Inc. All rights reserved v

8 Lesson Objectives 257 Inserting and Updating 258 Persisting a New Entity 259 Synchronization To the Database 260 Updating a Persistent Instance 261 Removing an Instance 262 Detached Entities 263 Lab 7.1: Inserting and Updating 264 Querying and Java Persistence Query Language (JPQL) 265 Java Persistence Query Language (JPQL) 266 JPQL Basics SELECT Statement 267 Querying and the TypedQuery Interface 268 Executing a Query 269 The Untyped Query Interface 270 Other Query Methods 271 Where Clause 272 JPQL Operators and Expressions 273 Query Parameters 274 Using Query Parameters 275 Named Queries 276 Named Queries 277 Lab 7.2: Basic Querying 278 Additional Query Capabilities 279 Projection Queries 280 Projection Queries Returning Tuples 281 Projection Query Returning Java Object 282 Additional Query Capabilities 283 Aggregate Queries 284 Aggregate Query Examples 285 Bulk Update and Delete 286 Native SQL Queries 287 Performance Considerations 288 Lab 7.3: More Querying 289 Session 8: Transactions 290 Lesson Objectives 291 Transactions and JPA 292 Transaction Overview 293 Transaction Lifecycle 294 Transactions Clarify Systems 295 JPA and Transactions 296 JPA Transaction Control 297 JPA EntityTransaction API 298 The EntityTransaction API 299 Spring Transaction Management 300 Spring's Transaction Managers 301 Configuring Transaction Managers 302 Spring's JTA Transaction Manager 303 Spring Declarative TX Management 304 Spring Transactional Scope 305 Transaction Propagation 306 Transaction Attributes for Propagation 307 MANDATORY 308 Copyright LearningPatterns Inc. All rights reserved vi

9 NESTED 309 NEVER 310 NOT_SUPPORTED 311 REQUIRED 312 REQUIRES_NEW 313 SUPPORTS 314 Mini-Lab: Transaction Example 315 Transaction Attributes - Some Choices 316 Transaction Attributes - Some Choices Configuration Declarative Transactions 319 Additional Transactional Attributes 320 Example: Specifying Transaction Attributes 321 Transactional Attributes Guidelines 322 Rolling Back and Exceptions 323 Aspect Oriented Programming (AOP) Defined 324 Aspect Oriented Programming Illustrated 325 Spring TX and AOP 326 Example Invoking Directly 327 Example Invoking Directly Pros and Cons 329 Lab 8.1: Spring Transactions 330 [Optional] Pointcut-based Configuration 331 Spring Transactions and AOP 332 Defining a Pointcut 333 Defining a Pointcut - XML 334 Specifying Transactions Using Pointcuts 335 Example: Pointcut-based Transactions (XML) 336 Linking Advice With Pointcuts 337 Resulting Behavioc 338 <tx:method> Attributes 339 Using Markers for Pointcuts 340 Marker Interface for TX Control 341 Marker Annotation for TX Control 342 Why Use Pointcut-based Configuration 343 More About Pointcut Expressions 344 Sample execution Designator Patterns 345 Sample execution Designator Patterns 346 Other Spring AOP Designators 347 Sample Designator Patterns 348 Review Questions 349 Lesson Summary 350 Session 9: The JPA Persistence Lifecycle 351 Lesson Objectives 352 The Persistence Lifecycle 353 The Persistence Lifecycle 354 JPA Entity States 355 Transient and Persistent State 356 Detached and Removed State 357 JPA Object States and Transitions 358 The Persistence Context 359 EM / Persistence Context Lifespan 360 EM-per-request 361 Copyright LearningPatterns Inc. All rights reserved vii

10 EM Propagation 362 Java SE and EM Propagation 363 The Persistence Context as Cache 364 Synchronization To the Database 365 Flushing the Entity Manager 366 Persistence Context and Object Identity 367 Yes, It's Complicated 368 Lab 9.1: EntityManager Behavior 369 Versioning and Optimistic Locking 370 Optimistic Locking 371 Using a Detached Instance 372 Using a Detached Instance Example 373 Versioning 374 Version Property in Java Class 375 Automatic Version Maintenance 376 Optimistic Locking Example 377 Explicitly Locking Objects 378 [Optional] Lab 9.2: Versioning (Demo) 379 Lifecycle Callbacks 380 Lifecycle Callbacks 381 Lifecycle Callback Example 382 When Lifecycle Callbacks are Invoked 383 Entity Listeners 384 Entity Listener Example 385 Lab 9.3: Lifecycle Callbacks 386 Review Questions 387 Lesson Summary 388 Lesson Summary 389 Session 10: Entity Relationships 390 Lesson Objectives 391 Relationships Overview 392 Object Relationships 393 Participants and Roles 394 Directionality 395 Diagramming Relationships 396 Cardinality 397 Mapping Relationships 398 Mappings Overview 399 Unidirectional Many-To-One Relationship 400 The Table Structure Many-To-One 401 The Owning Side 403 Using the Relationship 404 Bidirectional One-To-Many Relationship 405 Mapping the One-To-Many Relationship 406 Managing the Bidirectional Relationship 407 More on the Inverse Side 408 More on the Collection Declaration 409 Other Collection Types 410 Lab 10.1: Relationships 411 Bidirectional One-To-One Relationship 412 Coding: Bidirectional One-To-One 413 Orphan Removal 414 Copyright LearningPatterns Inc. All rights reserved viii

11 Many-To-Many Relationship 415 Defining Many-To-Many Relationship 416 Mapping Many-To-Many Relationships 417 Specifying the Join Table 418 Cascading Operations 419 Transitive Persistence 420 The cascade element 421 Choosing Cascade Behavior 422 Lazy and Eager Loading 423 Queries Across Relationships 424 OUTER and FETCH JOIN 425 FETCH JOIN Example 426 Lab 10.2: Working With Relationships 427 Mapping Inheritance 428 Inheritance Review 429 Entity Inheritance 430 Details of Entity Inheritance 431 Single-Table Strategy 432 Entity Definitions for Single-Table 433 Sample Table Entries 434 Single-Table: Pros and Cons 435 Joined (Table per Subclass) 436 Entity Definitions for Joined 437 Sample Table Entries: Table per Subclass 438 Joined: Pros and Cons 439 Table per Concrete Class 440 Lab 10.3: Working With Inheritance 441 Review Questions 442 Review Questions 443 Lesson Summary 444 Lesson Summary 445 Lesson Summary 446 Session 11: Spring / Web Integration (Regular Web Apps) 447 Lesson Objectives 448 Integration with Java EE 449 Spring and Java Enterprise Edition (JEE) 450 Overview of JEE Web Applications 451 Web Application Structure 452 Web Application Components 453 ApplicationContext and Java Web Apps 454 Configuring ContextLoaderListener - XML 455 ContextLoaderListener 456 Using the Application Context 457 Lab 11.1: Spring and the Web (Demo) 458 Open EntityManager in View 459 Problems with Web Applications 460 Open EntityManager In View Pattern 461 Servlet Filter - Open EntityManager In View 462 Spring's OpenEntityManagerInViewFilter 463 Configuring OpenEntityManagerInViewFilter 464 Using OpenEntityManagerInViewFilter 465 Lab 11.2: JPA and Web Apps (Demo) 466 [Optional] Session 12: Spring Data Introduction 467 Copyright LearningPatterns Inc. All rights reserved ix

12 Spring Data Overview 468 Why do We Need Spring Data 469 Spring Data Goals 470 Spring Data Project 471 Spring Data Modules 472 POM for Using Spring Data JPA 473 Using Spring Data 474 How is Spring Data (JPA) Structured? 475 CrudRepository/JpaRepository Methods 476 Mini-Lab: Review Javadoc 477 The Event Repository Type 478 Structure of our Repository 479 Using the Repository 480 Using Other CrudRepository Methods 481 [Optional] Lab 12.1: Using Spring Data 482 Defining Queries Using Naming Conventions 483 More About Generated Queries 484 More Complex Queries 485 Configuring Results 486 Defining Queries with JPQL 487 Spring Data JPA and Transactions 488 Lab 12.2: Writing Query Methods 489 Lesson Summary 490 [Optional] Session 13: Additional Features 491 Spring 5: Core Updates 492 Specification Baselines 493 Lambdas for Bean Registration 494 Default Interface Methods 495 Candidate Component Index 497 JPA: Embedded Objects 498 Using Embedded Objects 499 Example: Embeddable Class 500 Reusing Embeddable Classes 501 Overriding Embedded Class Attributes 502 JPA: Compound Primary Keys 503 Compound Primary Keys 504 Compound Key With Embedded Id Class 505 Example: Using an Embedded Id Class 506 Compound Key With Id Class 507 Compound Key With Id Class 508 JPA: Element Collections 509 Element Collections 510 Modeling a Collection of Strings 511 Mapping an Element Collection (Basic Type) 512 Using an Element Collection 513 Collections of Embeddable Components 514 Mapping Collections of Embeddables 515 Recap 516 Recap of what we've done 517 Resources 518 Copyright LearningPatterns Inc. All rights reserved x

13 Introduction Version: Version: Spring Base: b JPA Base:

14 Introduction Workshop Overview An in-depth course teaching the use of Spring 5 and JPA 2 to build data-driven enterprise Java applications And demonstrate best practices for Spring and JPA The course covers the following areas of Spring technology Architecture and core features of Spring Spring Boot Data Access Features including Spring Data JPA Architecture and Features Mapping and Querying Persistent Objects with JPA Transaction Support (and its AOP Foundation) JPA Associations Mapping JPA Inheritance Mapping Integration with Web Applications 2

15 Introduction Workshop Objectives: Spring Capabilities Understand the Spring framework and use its capabilities, including: Spring Core: Dependency Injection (DI) and bean lifecycle management Spring configuration and API for writing Spring programs XML, Java-based, and annotation-based config Spring Boot: Easing dependency management and configuration Spring Testing: JUnit intro and Spring testing support Data Access: Data access via Spring's data support DataSource support and JPA-based Repositories Spring Data based repositories Transactions: Controlling transactions declaratively with Spring Web: Integrating Spring with Web applications Including JPA repositories 3

16 Introduction Workshop Objectives: JPA Capabilities Understand and use JPA capabilities, including: Object Mapping: Create applications using JPA to map persistent Java objects to a relational database Understand and use the Entity Manager Understand the lifecycle of managed entities Query: Create and execute JPA queries using JPQL Associations: Map collections and associations using JPA Inheritance: Model inheritance with JPA 4

17 Introduction Workshop Agenda Session 2: Configuration in Depth Session 3: Intro to Spring Boot Session 4: Spring Testing Session 5: Intro to the JPA Session 6: Spring / JPA Integration Session 7: JPA Inserts and Queries Session 9: The JPA Persistence Lifecycle Session 10: JPA Entity Relationships Session 11: Spring / Web Integration (Regular Web Apps) Session 12: Spring Data Introduction Session 8: Transactions [Optional] Session 13: Additional Features 5

18 Introduction Typographic Conventions Code in the text uses a fixed-width code font, e.g.: Catalog catalog = new CatalogImpl() Code fragments are the same, e.g. catalog.speaktruth() We bold/color text for emphasis Filenames are in italics, e.g. Catalog.java Notes are indicated with a superscript number (1) or a star * Longer code examples appear in a separate code box - e.g. package com.javatunes.teach; public class CatalogImpl implements Catalog { public void speaktruth() { System.out.println("BeanFactories are way cool"); } } (1) If we had additional information about a particular item in the slide, it would appear here in the notes. We might also put related information that generally pertains to the material covered in the slide. 6

19 Introduction Labs Lab The workshop has numerous hands-on lab exercises, structured as a series of brief labs Many follow a common fictional case study called JavaTunes An online music store The lab details are separate from the main manual pages Setup zip files are provided with skeleton code for the labs Students add code focused on the topic they're working with There is a solution zip with completed lab code Lab slides have an icon like in the upper right corner of this slide The end of a lab is marked with a stop like this one: STOP 7

20 Overview Spring Introduction Dependency Injection 8

21 Lesson Objectives Understand why we need the Spring Framework Understand what Spring does, and how it simplifies enterprise application development Learn how Spring uses configuration information and Dependency Injection (DI) To manage the beans (objects) in an application To manage bean dependencies 9

22 Overview Overview Spring Introduction The Spring Container Dependency Injection 10

23 Spring and Enterprise Applications Enterprise apps have complex requirements, including Many application types and dependencies Persistent data and transactions Remote clients (REST, Web Service, others) Spring: Lightweight framework to build enterprise apps Non-intrusive, use only what you need, supports advanced capabilities Capabilities include: Dependency Injection (Inversion of Control/IOC) to manage bean dependencies DAO/Repository/Transaction support for persistent data ORM support (Object-relational mapping, e.g. JPA) AOP: Aspect-oriented programming Web: Integration with standard JEE Web apps Spring MVC: Model-View-Controller Web framework Security: Authentication and authorization There really is no formal definition of an enterprise application. Typically though, some of the characteristics they have are: Used in a business environment, often in business-critical domains. Have some form of persistent storage. Have some form of remote access (Web/HTTP, Web service, Distributed Objects, etc). Require some measure of scalability and fault tolerance. The definition of enterprise application is not important. Many Java applications share some of the requirements that we are outlining here. DAO: Data Access Object. The Spring ecosystem is now very large. There are other capabilities that we don't list and won't cover in this course. We'll cover some of the more central technologies that many of the others rely on. 11

24 The Spring Modules Module diagram from the Spring Reference Documentation 12

25 The Spring Distribution Spring home page: Distributed as modules in separate jars e.g. spring-beans release.jar Has external dependencies - e.g. logging, JUnit, etc. (1) Generally use a tool like maven for dependencies We supply jars the jars for some labs, and use maven in others Spring vs. JEE (Java Enterprise Edition) (2) JEE similarly supports enterprise apps e.g. CDI for lifecycle / dependency injection Which to use? What works best Based on your current and future system needs You might use both - e.g. a JEE Web container With Spring for lifecycle management and DI Or Spring MVC layered on top of JEE Servlets/JSP In earlier releases (up to Spring 3), both the Spring distribution and its dependencies were available as a separate download from the Spring download pages. These are no longer provided. It is assumed that you'll use a build tool like maven to get the Spring libraries and its dependencies. (1) The external dependencies for the core modules for dependency injection are (purposely) minimal. Basically you just have a logging framework. For other capabilities (e.g. AOP) there are more dependencies, but they're still rather small. If you use other technologies however, e.g. Hibernate/JPA, then there are more external dependencies. (2) Modern releases of Java/JEE offer many of the core capabilities of Spring. However, it is not productive to try to compare them in an absolute sense. Usually there are many constraints and requirements guiding your choice of technology. We'll present Spring's capabilities, strengths, and weaknesses, to support your decision making. 13

26 The Spring jars At right, are the Spring libraries we supply for the early labs (1) They are a subset of Spring Later labs, which need more jars, use maven for dependencies These are external dependencies (2) Again, just a subset of what we'll need in later labs (1) We supply the Spring project jars needed for the early labs in the lab setup. We downloaded these using maven and a pom.xml specifying the different modules available in Spring (e.g. spring-context) then gathered the jars together for the lab setup. The dependencies were done in the same way. Note that the actual jars in the lab setup may vary from this illustration - look at the setup to see what is actually used. Note that the junit and hamcrest jars are not needed by Spring, but needed because we use JUnit in our labs. (2) You can see that there are not a large number of external dependencies for the basic Spring functionality. You'll see when we do later, more complex, labs, that maven will include/download quite a few additional dependencies. 14

27 A Word About JUnit JUnit: Open source Java testing framework Often used in examples and labs to test our work Labs also create console output - that's not standard (see notes) JUnit capabilities include: Annotations for declaring test methods Assertions for testing expected results Test fixtures for sharing common data Test runners for running tests See next slide for an example We'll review in more depth in the Testing session Most development environments have JUnit support We'll use them to run tests which drive the lab code The tests are annotated methods (see next slide) We are using JUnit to drive our slide examples and lab code because it's convenient. And also because it gives an easy way to test lab results. However, since this is a class for learning new things, we often want some console indication of what's going on, so we'll produce some console output in our test classes. That's not usually done in test classes written explicitly for testing, but it's good for our purposes. We don't need to adhere to any particular testing practices - our test cases are lab-oriented, not for system testing. Where appropriate, we do adhere to standard conventions - e.g. in naming our test classes and test methods. 15

28 JUnit Example To write a JUnit test, we: Create a class, one or more methods annotated Make assertions using static methods in org.junit.assert (e.g. asserttrue) Note on testcontextnotnullpositive() The test creates the application context, and checks that it's non-null We use org.junit.assert.assertnotnull to perform the test See notes about import static and asserttrue usage // JUnit relevant code shown - some imports / code omitted import static org.junit.assert.*; import org.junit.test; public class SpringTests public void testcontextnotnullpositive() { ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(); // Just an example - we'd probably never test that the new operator works assertnotnull("spring container should not be null", ctx); } } The assertxxx methods are all static method of Assert. The familiar way to use these methods would be to import org.junit.assert, and then call the static methods through the Assert class. Assert.assertTrue(collection.isEmpty()); This is a little cumbersome, so the static import feature of Java is used - which imports static members from a class. The following import statement imports all the static members (including methods) from the Assert class. import static org.junit.assert.*; This allows us to use the static members without qualifying them by the classname, as seen in our earlier code. asserttrue(collection.isempty()); There is much more capability in JUnit. We won't go into that, since it's beyond the scope of the course. We only cover enough to show how the labs work. The course is also NOT meant to teach JUnit or JUnit best practices. 16

29 Lab 1.1: Setting Up the Environment In this lab you'll set up the lab environment, boot the Spring container, and test it with a unit test 17

30 Spring Introduction Overview Spring Introduction Dependency Injection 18

31 Managing Beans: Core Spring Capability Beans: Fancy name for application objects They're POJOs (Plain Old Java Objects) The Spring container is the "manager" Uses configuration information (metadata) to define, instantiate, configure, and assemble beans Metadata: Information about your beans (e.g. bean definitions) Container uses the configuration to create and manage beans (1) Configuration choices include XML and annotations XML: The "classic" configuration from early Spring Two annotation We'll cover all of these The term bean doesn't mean that much - it's a common name (e.g. JavaBeans and EJB). Here, we use it to mean an object managed by the Spring container. Spring Container: Software environment to manage beans and other capabilities. Also called the Dependency Injection (DI) or Inversion of Control (IoC) container. Programming to Spring basically means interacting with this software environment. (1) Spring will create and initialize bean instances based on your configuration data. You can then request those instances from the Spring container by type or name. We'll see how this works soon. Configuration metadata can also be provided in the Java properties format, or even provided programmatically (using Spring's public API). These are generally more cumbersome to use, and we won't cover them in this course. In fact, the Spring IoC container is totally decoupled from the external form of the metadata. It has its own internal format which it uses to store this information. The XML format was the original one, and is still in use today, but there are now other, more sophisticated, ways to configure the container. 19

32 A Basic Spring Application 20

33 The JavaTunes Online Store The course uses JavaTunes as an example and lab domain A simple online music store (1) Some of the types you'll see include: com.javatunes.domain.musicitem : JavaBean-style value class representing a music item (e.g. an mp3) com.javatunes.service.catalog : Interface defining JavaTunes catalog functionality (including search) com.javatunes.service.catalogimpl : Concrete Catalog implementation (uses ItemRepository) com.javatunes.persistence.itemrepository : Interface defining data access API for items com.javatunes.persistence.inmemoryitemrepository : Concrete ItemRepository implementation (simple in-memory storage) (1) We use a simple online music store as our domain for examples in the slides and for the labs. We've tried to give it enough detail to provide good material to work with while keeping it simple enough so you don't have to spend too much time in figuring it out. 21

34 Some JavaTunes Types Catalog and CatalogImpl are shown below Note how CatalogImpl implements the Catalog interface (1) Let's look at how to configure some objects package com.javatunes.service; public interface Catalog { public MusicItem findbyid (long id); public Collection<MusicItem> findbykeyword(string keyword); public long size(); } package com.javatunes.service; public class CatalogImpl implements Catalog { // Detail omitted } public MusicItem findbyid (long id) { /* */ } public Collection<MusicItem> findbykeyword(string keyword) { /* */ } public long size() { /* */ } These two types are part of JavaTunes. We'll use them to motivate our discussion on how Spring works. (1) Programming to interfaces provides many advantages by decoupling your code from concrete implementation classes. This is not a concept unique to Spring. Many design patterns are based on the decoupling gained by programming to an interface. We'll soon see how the Spring framework makes these advantages even more usable and powerful by helping manage the dependencies that have been abstracted using interfaces. 22

35 XML Configuration Example Spring can be configured in an XML file Default config file: applicationcontext.xml, but can be anything (1) General structure: Top level <beans> containing <bean> elements Each <bean> defines a bean Generally specify id (a name) and class (fully qualified class name) (2) Supports other configuration also - we'll cover it as we encounter it At bottom, we define one bean with XML (the metadata) Many existing applications use XML But annotation-based approaches now recommended <?xml version="1.0" encoding="utf-8"?> <!-- The beans namespace is the default one for the document --> <beans xmlns=" xmlns:xsi=" xsi:schemalocation=" <bean id="musiccatalog" class="com.javatunes.service.catalogimpl"/> </beans> (1) applicationcontext.xml is a standard (and default) name for the Spring config file, but you can name it anything that you want. In fact, as we'll see, you can have multiple config files. (2) There are more sophisticated ways to create beans, for example with a factory class (shown later), in which case the class name may not be the actual implementation class. Spring provides an XML Schema for this configuration file, and the examples and lab setup files have the necessary XML namespace information in them to refer to this schema. This is standard XML usage, and we don't go into the details here of how to use an XML Schema. Refer to an XML reference if you need more detail on this. The xsi:schemalocation property in the slide doesn't specify a version number for the schema. The latest version will automatically be picked up. For example, spring-beans-4.3.xsd (latest current version in Spring 5 as of this writing). You read that correctly, the latest schema version is 4.3, even for Spring 5. Typically configure beans like service and repository objects, Hibernate sessions, JMS queues, etc. Some BeanFactory implementations also permit the registration of existing objects that have been created outside the factory (by user code). 23

36 The Spring Container The Spring container Reads your configuration, and based on it: Instantiates/initializes application objects Resolves object dependencies org.springframework.context.applicationcontext Core API to access the Spring container in your code Several implementations with different capabilities, e.g. ClassPathXmlApplicationContext: Loads XML resources from the class path Interface ApplicationContext extends BeanFactory BeanFactory has many core methods - usually not used directly Interface BeanFactory is in package org.springframework.beans.factory. 24

37 Instantiating and Using the Container Below, we create a ClassPathXmlApplicationContext Sometimes called "instantiating the container" We pass the name of our config file (or multiple file names) The container will create and manage the beans defined in the XML Next, we look up our configured bean via the context Looked up by type (Catalog.class) - can look up by name also (1) We do any needed work, then close the context import org.springframework.context.support.classpathxmlapplicationcontext; // Code fragment - other imports and much detail omitted ClassPathXmlApplicationContext ctx= new ClassPathXmlApplicationContext("applicationContext.xml"); // Note that getbean uses Java generics (no casting needed) Catalog cat = ctx.getbean(catalog.class); // Or lookup by name: ctx.getbean("musiccatalog", Catalog.class); MusicItem item = cat.findbyid(1l); // Use our bean ctx.close(); // Close the context Creating an instance of an ApplicationContext is often called "instantiating" or "bootstrapping" the container. When the instance is created, it reads the configuration. Based on the configuration, it does whatever work it needs to get ready to supply you with beans. We then use that context instance to interact with the container. It contains the API that you have access to. (1) It's generally easier and more reliable to look up beans by their type. However, sometimes that's not practical or possible - for example when there is more than one concrete implementation of an interface. We'll see bean lookup by name later. We can pass multiple config files when creating the context, for example as shown below. ApplicationContext ctx = new ClassPathXmlApplicationContext( "ctx-1.xml", "ctx-2.xml" ); 25

38 Why Bother - What do we Gain? Main benefit: Our code doesn't know about CatalogImpl It just knows about needed functionality (interface Catalog) We've decoupled our code from a dependency on the implementation class Can use any implementation in our configuration Client code will not change That's why we code to interfaces, not concrete types Bean lifecycle is managed by container We don't instantiate our beans directly Very useful for more complex systems We'll see more useful capabilities soon In this simple example, it looks like we've done quite a bit of work to instantiate a single instance of a single class. What is the benefit? The decoupling we've achieved seems like a simple thing, but it has a lot of benefits, especially when maintaining large systems. We'll see how useful it can be when we explore more of the capabilities. 26

39 Summary: Working With Spring Create Spring configuration data for your beans It's the "cookbook" telling Spring how to create objects Via an XML file like applicationcontext.xml or via annotations Initialize the Spring container e.g.create an application context instance to read config data It will initialize the beans in the config file(s) Retrieve beans via the context instance and use them e.g. use getbean() to look up a bean by type or name Lookup by type is preferred, unless you can't do it For instance, if you have two beans implementing the same type There are many, many usage scenarios for Spring. And many, many different alternatives for each scenario Spring is very large, and has a lot of flexibility and capability In this initial introduction we show you one straightforward way of using Spring. We will gradually introduce more capabilities throughout the course. 27

40 More on ApplicationContext Access point for many Spring capabilities, including: Bean access Resource Access: Config files, URLs, other files Message resources with I18N capability Publishing events to managed beans that are listeners Multiple, hierarchical contexts ClassPathXmlApplicationContext Loads XML config files from the classpath FileSystemXmlApplicationContext Loads XML config files from the file system or URLs Both in org.springframework.context.support AnnotationConfigApplicationContext Accepts annotated classes as input (more on this later) In org.springframework.context.annotation The ApplicationContext is the full-fledged representation of the Spring container. It is often regarded as the type that supplies the "framework" capabilities of Spring, rather than simple bean management. If you are writing applications for a very resource-restricted environment, such as a mobile device, you might consider using BeanFactory over ApplicationContext. Then again, even mobile devices these days usually have enough capability to make the additional resources used by ApplicationContext negligible. There are also Web-based application contexts we'll cover later. We'll cover the ApplicationContext API in various parts of the course. 28

41 Some BeanFactory/ApplicationContext API Useful methods include: boolean containsbean(string): true if named bean exists <T> T getbean(class<t> requiredtype): Get by type <T> T getbean(string, Class<T> requiredtype): Get by name Class<?> gettype(string name): Get type of named bean boolean issingleton(string): Is bean a singleton String[] getaliases(string): Get any aliases for this bean Many more methods - see the javadoc Can specify config files in multiple ways ant-style wildcards: e.g. conf/**/ctx.xml - All ctx.xml files under conf file: and classpath: prefixes - forces use of specified location, e.g. The following loads from the classpath: new FileSystemXmlApplicationContext("classpath:ctx.xml"); Spring uses its resource classes under the hood to do this The methods shown are a part of the BeanFactory API inherited by ApplicationContext. getbean returns either a singleton (shared) instance, or a newly created bean. NoSuchBeanDefinitionException thrown if the bean can't be found BeansException thrown if an exception occurred while instantiating/preparing the bean BeanNotOfRequiredTypeException thrown if the bean is not of the required type Object getbean(string) returns an object which is then cast to the required type. The newer getbean(string,class<t> requiredtype) method is generally preferred. gettype(string) throws NoSuchBeanDefinitionException if the bean can't be found. issingleton(string) throws NoSuchBeanDefinitionException if bean can't be found. The method <T> T getbean(string, Class<T> requiredtype) may look strange. This is standard Java generics syntax - The first <T> in the return type simply indicates that this is a generic method, parameterized by the type parameter <T>. The T return value indicates that the return type is generic (that is, it will take on different types based on the <T> parameter). The Class<T> argument indicates that when you call the method, you pass in the class which specifies what type <T> actually is in that call. 29

42 We provide the Spring Javadoc Mini-Lab: Review Javadoc Mini-Lab Under StudentWork/Spring/Resources/SpringDocs/javadoc In a browser, open index.html in the folder above Review the javadoc for the following types BeanFactory ApplicationContext ClassPathXmlApplicationContext (especially the constructors) FileSystemXmlApplicationContext (especially the constructors) 30

43 Lab 1.2: Hello Spring World In this lab, we will create and use a Spring context to access a bean instance 31

44 Annotation-Based Configuration Example Beans can be declared with (org.springframework.stereotype) - Spring often called a "stereotype" (javax.inject) - Standard Java (JSR 330) annotation We'll use Spring style annotations in this course (1) declares CatalogImpl as a bean Specifies id as musiccatalog (Default id: catalogimpl) Same bean as previous XML example Could also have import org.springframework.stereotype.component; package // Declares bean with id musiccatalog public class CatalogImpl implements Catalog { /* Most detail omitted */ } (1) Common usage in Spring projects is to use the Spring-based annotations. Some advocate the usage of JSR-330 annotations since they are a Java standard. This would (theoretically) allow you to port to another container that uses JSR-330 annotations - for example JEE and its CDI capabilities. However, this would entail a lot more work than just the annotations on the beans, so we don't consider this much of a benefit, especially since it's relatively rare to do this kind of transition. In addition, the behavior of the JSR-330 annotations in the Spring container are not exactly the same as in a JEE container, so using them is somewhat misleading. All these considerations lead us to choose the Spring-standard annotations over the JSR-330 annotations when working with Spring. 32

45 A Brief Note on Annotations Standard Java mechanism to add metadata to source code Like comments that the compiler is aware is used for both declaration and use of annotations (1) Annotations don't directly affect program semantics They are not executable code Tools work with the annotated code And may affect the semantics of a running annotated beans are recognized as bean defs by the Spring container (1) There is a syntax for declaring annotations, a syntax for using them in declarations, a class file representation, and an API to read them. We'll only cover the capabilities that we'll be using for our Spring coding. Annotations can replace many "side files" e.g. XML deployment descriptors. It's easier for tools to read the metadata and source if they're all in one place. They're often used for specifying details of high-level technologies (e.g. AOP, EJB, Web Services ). These often result in code generation. Annotations are present in the class file, and can be read by tools. The JDK also comes with a command line utility, called apt (Annotation Processing Tool), that can be used to process annotations. 33

46 Enabling Annotations / Detecting Beans Spring can automatically scan for annotated beans on the classpath This registers them as normal beans Enable auto scanning via <context:component-scan/> A standard element from Spring's context namespace (see next slide) Includes the capabilities of <context:annotation-config/> (1) basepackage attribute configures the packages to scan <beans xmlns=" xmlns:xsi=" xmlns:context=" xsi:schemalocation=" <context:component-scan base-package="com.javatunes"/> </beans> (1) In addition to enabling scanning, context:component-scan also enables the capabilities of context:annotation-config. context:annotation-config activates the ability to detect annotations It only affects beans that are already registered. component-scan element in the slide example will scan for all components in the com.javatunes package and all of its sub-packages, and register them as beans. Note that annotations are actually detected by bean postprocessors (not important to know, but interesting if you want to know a bit about Spring internals). There are other attributes to component-scan, including annotation-config: (default true): should the implicit annotation post-processors (AutowiredAnnotationPostProcessor, CommonAnnotationPostProcessor) be registered resource-pattern: Controls the class files eligible for component scanning. Default is **/*.class, the recommended value 34

47 Overview - Spring's XML Schemas Spring provides XML Schemas for configuration With custom namespaces and tags with complex behavior (1) e.g. the context: namespace we just used Spring namespaces include: aop: Configures AOP support beans: The standard bean tags we've seen already context: Configures ApplicationContext related things jee: JEE related configuration such as looking up a JNDI object jms: Configures JMS related beans lang: Exposing objects written in language like JRuby as beans tool: Adds tooling-specific metadata tx: Configures transaction support util: Common, utility configuration issues (1) We've seen the usage of <context:component-scan> previously. It is is a shorthand to introduce a number of bean definitions into the configuration. The tags in these schemas typically have capabilities beyond simple bean definitions and injection. This is one of the nice things about the custom namespaces - they can make configuration much easier. 35

48 Lab 1.3: Spring Annotations In this lab, we'll work with Spring Annotations 36

49 Dependency Injection Overview Spring Introduction Dependency Injection 37

50 Dependencies Between Objects In OO systems, multiple objects work together e.g., Object A directly uses Object B to accomplish a goal (1) So Object A depends on Object B Direct dependencies have several issues Rigid: Changes affect other areas, so are hard to make Fragile: Changes cause unexpected failures in other areas Immobile: Hard to reuse functionality Modules can't be disentangled We'll illustrate a direct dependency Then show an alternative approach (1) In straightforward applications, Object A will often just create an instance of Object B and use it. Object A is highly coupled to, and directly dependent on, Object B. This is initially an easy way to structure a system, but often not the best way. 38

51 Example of a Direct Dependency CatalogImpl uses InMemoryRepository And creates an InMemoryRepository instance directly CatalogImpl depends on the lower level module details To use a different data store - e.g. a FileRepository, CatalogImpl must change (see notes) public class InMemoryItemRepository { public MusicItem get(long id) { /* Details not shown */ } } public class CatalogImpl implements Catalog { InMemoryItemRepository rep = new InMemoryItemRepository(); public MusicItem findbyid(long ID) { return rep.get(id); } } Assume we want to get our information from a class called FileRepository. Assume it also has a get(long id) method. In that case, CatalogImpl might need to be changed to something like that below. public class CatalogImpl implements Catalog { } FileRepository rep = new FileRepository(); public MusicItem findbyid(long id) { } return rep.get(id); This is not such a big deal if you have to change it in one place. But imagine if you had to change it in 100 places, or 10,000 places. Assume that classes in the examples in this session are in the com.javatunes.service package. We'll be leaving out most package statements in the Java code examples for brevity. 39

52 Dependency Inversion All modules depend on abstractions, not each other In other words - program to interfaces CatalogImpl only knows about the abstract ItemRepository Can be initialized with another type (e.g. FileItemRepository) CatalogImpl need not change - the modules are decoupled public interface ItemRepository { public MusicItem get(long id); } // Much detail omitted public class InMemoryItemRepository implements ItemRepository { /* */ } public class CatalogImpl implements Catalog { private ItemRepository itemrepository; // get/set methods not shown public MusicItem findbyid(long id) { return itemrepository.get(id); } } // Code fragment - most detail omitted InMemoryItemRepository rep=new InMemoryItemRepository(); CatalogImpl catalogimpl=new CatalogImpl(); catalogimpl.setitemrepository(rep); MusicItem found = catalogimpl.findbyid(1); Dependency Inversion is not a new idea. The idea of "Programming to Interfaces" has been around since long before Java. It has been used in non-oo languages also, for example the stdio module in the C programming language abstracted away the details of the actual devices doing the output. We'll soon look at Spring's Dependency Injection which makes this design strategy even easier to use. We talk of modules here, which in this example result in dependencies between different classes. In the example, we see that CatalogImpl knows nothing about InMemoryItemRepository. It only depends on the ItemRepository interface (the abstraction). When CatalogImpl is created, you initialize it with an instance of an ItemRepository implementation. But it doesn't know any details of this implementation, and doesn't even know its exact type. InMemoryItemRepository also depends on the abstraction (it implements ItemRepository ). The abstraction (the interface) is the common language that lets the different parts of the system work together without depending directly on each other. We are still creating the InMemoryItemRepository directly in our code (in this example). We'll have Spring do this soon, which gives even more benefit. 40

53 Dependency Injection (DI) in Spring The Spring container injects dependencies into a bean Into bean properties, constructors, or via factory method args Dependencies are defined in the Spring configuration Spring initializes the dependencies ("injects" them) based on the config No need to explicitly initialize dependencies in your code We illustrate XML config of this below (injecting via a set method) <property > injects into the catalog's itemrepository property Automatically done when the container creates the bean <beans > <!-- Much detail / Namespace declarations omitted --> <bean id="inmemoryrepository" class="com.javatunes.persistence.inmemoryitemrepository"/> <bean id="musiccatalog" class="com.javatunes.service.catalogimpl"> <property name="itemrepository" ref="inmemoryrepository"/> </bean> </beans> 41

54 Injection with Autowired Can also inject - shown below for the repository This injects a dependency by type - same result as previous XML At bottom, we get a catalog from Spring With an already initialized repository (by Spring's DI) We're ready to work! import org.springframework.stereotype.component; import // Declares bean - most detail omitted public class CatalogImpl implements Catalog // can also apply to setter method or constructor private ItemRepository itemrepository; } public class CatalogTests { // imports, other detail testcatalogfindbyid() { ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); Catalog cat = ctx.getbean(catalog.class); // See note (1) assertnotnull("item shouldn't be null", cat.findbyid(1l)); // Use cat } (1) The bean lookup with the code shown directly below works because there is only one bean that implements Catalog, so the container can find this bean by type. ctx.getbean( Catalog.class ); We'll see ways to refine this type of lookup later. Note that CatalogImpl and InMemoryItemRepository didn't need anything special to support Spring's DI. They just need to be written according to the design principles of Dependency Inversion (i.e. coding to an interface, not a concrete type) which is good practice anyway. Once this was done, we didn't need any special capabilities to support DI. Note also that there is nothing in your CatalogTests code which shows that CatalogImpl depends on InMemoryRepository. This is defined in your configuration, and handled for you by the container. 42

55 (JSR-330) Example is used to declare a is used to inject the dependency Results are the same as style And the test client would look exactly the same We'll style going forward, as mentioned earlier It's the more common choice import javax.inject.inject; import // Declares bean - most detail omitted public class CatalogImpl implements Catalog private ItemRepository itemrepository; } 43

56 Dependency Injection Reduces Coupling The simplest case, CatalogImpl coupled to InMemoryItemRepository CatalogImpl InMemoryItemRepository CatalogImpl coupled to ItemRepository only (Dependency Inversion) CatalogTests coupled to CatalogImpl and InMemoryItemRepository CatalogImpl creates CatalogTests creates <<interface>> ItemRepository implements InMemoryItemRepository Using DI CatalogTests only coupled to Catalog CatalogImpl only coupled to ItemRepository <<interface>> Catalog looks up implements injects CatalogImpl <<interface>> ItemRepository CatalogTests ApplicationContext In the slide, we show diagrams of the three different ways we structured our code in the earlier slides. In the first, CatalogImpl is directly coupled to InMemoryItemRepository. In the second, CatalogTests is doing the dependency injection of the InMemoryItemRepository into CatalogImpl. CatalogTests is coupled to both of these types, but CatalogImpl is only coupled to ItemRepository. In the third, Spring is doing the DI, and so CatalogTests and CatalogImpl are only coupled to abstract interfaces. In the Spring DI version, all the dependencies in the code are ONLY to interfaces. This is much better than being coupled to actual implementation classes. It increases flexibility, testability, and ease of maintenance. 44

57 Advantages of Dependency Injection Hides dependencies and reduces coupling in your code Coupling is basically a measure of the dependencies We see this in two ways: CatalogImpl is not coupled to InMemoryItemRepository CatalogTests is not coupled to CatalogImpl or InMemoryItemRepository The dependencies are still there but not in the code Dependencies are moved to the spring configuration They're injected into beans without you coding it Commonly referred to as wiring beans together This leads to more flexible code that is easier to maintain At a cost using Spring, and maintaining the spring configuration Coupling is the measure of how much a module of code relies on other modules. Loosely coupled code is generally considered better code. Consider some of the following scenarios, and how DI makes them easier. Testing your code with a testing framework such as JUnit can be much easier with DI you can configure the application to use mock objects wherever you want without changing your code at all. Testing different versions of classes can be done just by changing the configuration metadata. In fact, any implementation class that implements the particular interfaces being used can be swapped into your program simply by changing the configuration information. There is debate about how worthwhile DI and frameworks like Spring are. However, the principles that it is based on that lead to loose coupling are widely accepted. Spring simply makes it easier to apply these principles. The effort required to learn, adopt, and use Spring is not trivial, but the initial cost of adopting Spring can be well worth it in writing and maintaining any reasonably sized system. 45

58 Constructor Injection Can easily inject into a constructor (ctor) Assume the CatalogImpl constructor shown below With XML, <constructor-arg> means "inject into constructor" apply it to the constructor See notes for some additional detail/capabilities public class CatalogImpl implements Catalog { // Most detail omitted public CatalogImpl(ItemRepository repository) { /* */ } } <!-- XML config - Other detail omitted --> <bean id="musiccatalog" class="com.javatunes.service.catalogimpl"> <constructor-arg ref="itemrepository"/> <!-- inject via ctor --> </bean> public class CatalogImpl implements Catalog { // Most detail // Inject into ctor below public CatalogImpl(ItemRepository repository) { /* */ } if there is only one constructor, you can even leave It will be inferred - but we believe it's better practice to include it explicitly. If a constructor has multiple arguments, they will all be injected For example, assuming that a CatalogImpl needs an ItemChecker to do some sanity checking on items, you might have the following ctor, which will have both arguments public CatalogImpl(ItemRepository rep, ItemChecker checker) In XML, multiple arguments would be handled with multiple <constructor-arg>s. <bean id="musiccatalog" <!-- inject two ctor arguments --> class="com.javatunes.service.catalogimpl"> <constructor-arg ref="itemrepository"/> <constructor-arg ref="itemcheck"/> <!-- itemcheck def not shown --> </bean> There are a lot of ways to configure the ctor injection. For example, you can specify the type and/or index of args with XML configuration. These details are best explored as needed in the documentation, not during class time. 46

59 Setter Injection vs. Constructor Injection Setter Injection Pros Easy, Flexible: Simple setters, easily choose properties to configure Good for optional properties (with defaults to reduce not-null checks) Supports reconfiguration after startup Setter Injection Cons Doesn't guarantee property initialization (Forget to do it - BUG!) Setter methods are required Constructor Injection Pros Guaranteed Initialization: Immediate error if you leave it out (1) Good for required properties (can be immutable if setter omitted) Constructor Injection Cons Unwieldy and Brittle: Multiple constructors with multiple args unwieldy Refactor if you have this Less flexible: Need ctors for each scenario, and can't reset properties (1) If you leave out a constructor argument while configuring a bean, you'll have an error. If using XML configuration you'll get a runtime exception as soon as the code is run. You can mix constructor and setter injection. For example, using constructor injection on required properties, and setter injection on other properties. 47

60 Qualifying Injection by Name Consider two repository implementations (first two examples below) What happens if we try to auto-wire one in? The first autowire below fails at runtime - which one to inject? The second try is "qualified" by the bean name It injects based on the bean // Declare as bean - default id inmemoryitemrepository public class InMemoryItemRepository implements ItemRepository { // Declare as bean - default id clouditemrepository public class CloudItemRepository implements ItemRepository { public class CatalogImpl implements Catalog { // private ItemRepository itemrepository; // FAILS! } import public class CatalogImpl implements Catalog { private ItemRepository itemrepository; // Injects the Cloud-based } In the first example of injection, where the autowiring is done by type, it fails at private ItemRepository itemrepository; // FAILS! The container doesn't know which of the two possible types to use. In the second example of injection we to supply a bean name. This pinpoints exactly which bean should be injected, and works as private ItemRepository itemrepository; // Injects the Cloud-based There are other, more sophisticated, ways to qualify an injection. This involves defining your own qualifiers, for instead of using names. This is compile-time safe, as it is not a string-based approach, so useful for program correctness. However, it's fairly complex, and arguably the complexity is often not worth the benefit. With adequate testing, name-based qualifying should work fine. In those instances (rare) when it's not suitable, then you can use the more sophisticated approach, which is beyond the scope of this course. 48

61 Lab 1.4: Dependency Injection In this lab, we'll work with Spring's DI capabilities 49

62 Review Questions What is Spring, and how does it help you build enterprise apps? What is Dependency Inversion? What is Dependency Injection, and how does it work in Spring What is an ApplicationContext? How does Spring use annotations on your bean classes for defining and wiring beans? What are the pros/cons of using them? 50

63 Lesson Summary Spring: Lightweight enterprise framework that supports: Dependency Injection Persistence support (Repository/DAO and ORM) Integration with standard Web technologies, and MVC Web apps Manages complex dependencies - non-intrusive and lightweight Supports loose coupling between components Encourages coding to interfaces (good design) Also called Dependency Inversion Uses configuration metadata to initialize beans and dependencies Via XML configuration files or annotations Dependency Injection: Injects dependencies based on config Complete decoupling from concrete implementation types 51

64 Lesson Summary ApplicationContext: API to the Spring container functionality Configure/wire beans, access program resources, work with resource bundles, load multiple contexts, and publish events to beans Common implementations include: ClassPathXmlApplicationContext, FileSystemXmlApplicationContext, and AnnotationConfigApplicationContext Provides resource access in a flexible and powerful way From file system, the classpath, URL access, and more Supports ant-style wildcards like conf/**/ctx.xml Uses its own resource classes to accomplish resource access 52

65 Introduction to Spring 5 and JPA 2 Lab Manual - Eclipse/Hibernate

66 This material is copyrighted by LearningPatterns Inc. This content and shall not be reproduced, edited, or distributed, in hard copy or soft copy format, without express written consent of LearningPatterns Inc. Copyright LearningPatterns Inc. For more information about Java Enterprise Java, or related courseware, please contact us. Our courses are available globally for license, customization and/or purchase. LearningPatterns. Inc. Global Courseware Services Main St. Ste Fishkill NY, USA voice and fax Java, and all Java-based trademarks and logo trademarks are registered trademarks of Oracle, Inc., in the United States and other countries. LearningPatterns and its logos are trademarks of LearningPatterns Inc. All other products referenced herein are trademarks of their respective holders.

67 Labs: Introduction Labs: Introduction to Spring 5 and JPA 2 (Eclipse/Tomcat) Version: Version: Spring Base: b JPA Base:

68 Labs: Introduction Release Level Lab This manual has been tested with, and contains instructions for, running the labs using the following platforms: Spring Boot (tested with RELEASE) Spring 5 (tested with RELEASE) Release used by Spring Boot JPA 2.2 (Using Hibernate 5.3) We override the Hibernate version used by Spring Boot Java (tested with and requires Java 8 ) Eclipse Java EE Edition (tested with Oxygen 4.7.3) Tomcat for the Spring/Web material (tested with Tomcat 8.5) Recent similar versions of the software will likely work except for potentially small configuration changes Any 5.x version of Spring should work. The course materials are compatible with all 5.x versions. However, we include some Spring jars and their dependencies with the labs. If you want to use a different version, then it's up to you to make sure you have all the correct Spring jars and the correct dependency jars. We will also introduce Maven and Spring Boot to manage all dependencies later in the course. Spring Boot 2 is needed to support Spring 5. At the time of this writing the latest release version was Spring Boot RELEASE. All labs have been tested on Microsoft Windows using the software listed above. Many have been tested on Mac OS also. The labs should work on unix variants with little modification, except for the database setup scripts, which need to use unix shell scripts, which we also supply. 2

69 Labs: Lab 1.2: Hello Spring World Lab 1.2: Hello Spring World In this lab, we will create and use a Spring context to access a bean instance 18

Fast Track. Evaluation Copy. to Spring 3.x. on Eclipse/Tomcat. LearningPatterns, Inc. Courseware. Student Guide

Fast Track. Evaluation Copy. to Spring 3.x. on Eclipse/Tomcat. LearningPatterns, Inc. Courseware. Student Guide Fast Track to Spring 3.x on Eclipse/Tomcat LearningPatterns, Inc. Courseware Student Guide This material is copyrighted by LearningPatterns Inc. This content and shall not be reproduced, edited, or distributed,

More information

Fast Track to EJB 3.0 and the JPA Using JBoss

Fast Track to EJB 3.0 and the JPA Using JBoss Fast Track to EJB 3.0 and the JPA Using JBoss The Enterprise JavaBeans 3.0 specification is a deep overhaul of the EJB specification that is intended to improve the EJB architecture by reducing its complexity

More information

Web Application Development Using Spring, Hibernate and JPA

Web Application Development Using Spring, Hibernate and JPA Web Application Development Using Spring, Hibernate and JPA Duration: 5 Days Price: 1,995 + VAT Course Description: This course provides a comprehensive introduction to JPA (the Java Persistence API),

More information

Web Application Development Using JEE, Enterprise JavaBeans and JPA

Web Application Development Using JEE, Enterprise JavaBeans and JPA Web Application Development Using JEE, Enterprise Java and JPA Duration: 35 hours Price: $750 Delivery Option: Attend training via an on-demand, self-paced platform paired with personal instructor facilitation.

More information

Web Application Development Using Spring, Hibernate and JPA

Web Application Development Using Spring, Hibernate and JPA Web Application Development Using Spring, Hibernate and JPA Duration: 5 Days US Price: $2795 UK Price: 1,995 *Prices are subject to VAT CA Price: CDN$3,275 *Prices are subject to GST/HST Delivery Options:

More information

Web Application Development Using Spring, Hibernate and JPA

Web Application Development Using Spring, Hibernate and JPA Web Application Development Using Spring, Hibernate and JPA Duration: 5 Days Price: CDN$3275 *Prices are subject to GST/HST Course Description: This course provides a comprehensive introduction to JPA

More information

Web Application Development Using JEE, Enterprise JavaBeans and JPA

Web Application Development Using JEE, Enterprise JavaBeans and JPA Web Application Development Using JEE, Enterprise Java and JPA Duration: 5 days Price: $2795 *California residents and government employees call for pricing. Discounts: We offer multiple discount options.

More information

ADVANCED JAVA TRAINING IN BANGALORE

ADVANCED JAVA TRAINING IN BANGALORE ADVANCED JAVA TRAINING IN BANGALORE TIB ACADEMY #5/3 BEML LAYOUT, VARATHUR MAIN ROAD KUNDALAHALLI GATE, BANGALORE 560066 PH: +91-9513332301/2302 www.traininginbangalore.com 2EE Training Syllabus Java EE

More information

Spring Interview Questions

Spring Interview Questions Spring Interview Questions By Srinivas Short description: Spring Interview Questions for the Developers. @2016 Attune World Wide All right reserved. www.attuneww.com Contents Contents 1. Preface 1.1. About

More information

Desarrollo de Aplicaciones Web Empresariales con Spring 4

Desarrollo de Aplicaciones Web Empresariales con Spring 4 Desarrollo de Aplicaciones Web Empresariales con Spring 4 Referencia JJD 296 Duración (horas) 30 Última actualización 8 marzo 2018 Modalidades Presencial, OpenClass, a medida Introducción Over the years,

More information

Introduction to Spring 5, Spring MVC and Spring REST

Introduction to Spring 5, Spring MVC and Spring REST Introduction to Spring 5, Spring MVC and Spring REST Duration: 5 Days US Price: $2795 UK Price: 1,995 *Prices are subject to VAT CA Price: CDN$3,275 *Prices are subject to GST/HST Delivery Options: Attend

More information

Fast Track to Spring 3 and Spring Web Flow 2.1

Fast Track to Spring 3 and Spring Web Flow 2.1 Fast Track to Spring 3 and Spring Web Flow 2.1 on Tomcat/Eclipse LearningPatterns, Inc. Courseware Student Guide This material is copyrighted by LearningPatterns Inc. This content and shall not be reproduced,

More information

Enterprise JavaBeans, Version 3 (EJB3) Programming

Enterprise JavaBeans, Version 3 (EJB3) Programming Enterprise JavaBeans, Version 3 (EJB3) Programming Description Audience This course teaches developers how to write Java Enterprise Edition (JEE) applications that use Enterprise JavaBeans, version 3.

More information

Fast Track to Spring 3 and Spring MVC / Web Flow

Fast Track to Spring 3 and Spring MVC / Web Flow Duration: 5 days Fast Track to Spring 3 and Spring MVC / Web Flow Description Spring is a lightweight Java framework for building enterprise applications. Its Core module allows you to manage the lifecycle

More information

CONFIGURING A SPRING DEVELOPMENT ENVIRONMENT

CONFIGURING A SPRING DEVELOPMENT ENVIRONMENT Module 5 CONFIGURING A SPRING DEVELOPMENT ENVIRONMENT The Spring Framework > The Spring framework (spring.io) is a comprehensive Java SE/Java EE application framework > Spring addresses many aspects of

More information

Spring & Hibernate. Knowledge of database. And basic Knowledge of web application development. Module 1: Spring Basics

Spring & Hibernate. Knowledge of database. And basic Knowledge of web application development. Module 1: Spring Basics Spring & Hibernate Overview: The spring framework is an application framework that provides a lightweight container that supports the creation of simple-to-complex components in a non-invasive fashion.

More information

CO Java EE 6: Develop Database Applications with JPA

CO Java EE 6: Develop Database Applications with JPA CO-77746 Java EE 6: Develop Database Applications with JPA Summary Duration 4 Days Audience Database Developers, Java EE Developers Level Professional Technology Java EE 6 Delivery Method Instructor-led

More information

Pro JPA 2. Mastering the Java Persistence API. Apress* Mike Keith and Merrick Schnicariol

Pro JPA 2. Mastering the Java Persistence API. Apress* Mike Keith and Merrick Schnicariol Pro JPA 2 Mastering the Java Persistence API Mike Keith and Merrick Schnicariol Apress* Gootents at a Glance g V Contents... ; v Foreword _ ^ Afooyt the Author XXj About the Technical Reviewer.. *....

More information

Java EE 7: Back-End Server Application Development

Java EE 7: Back-End Server Application Development Oracle University Contact Us: Local: 0845 777 7 711 Intl: +44 845 777 7 711 Java EE 7: Back-End Server Application Development Duration: 5 Days What you will learn The Java EE 7: Back-End Server Application

More information

JVA-163. Enterprise JavaBeans

JVA-163. Enterprise JavaBeans JVA-163. Enterprise JavaBeans Version 3.0.2 This course gives the experienced Java developer a thorough grounding in Enterprise JavaBeans -- the Java EE standard for scalable, secure, and transactional

More information

"Charting the Course... Mastering EJB 3.0 Applications. Course Summary

Charting the Course... Mastering EJB 3.0 Applications. Course Summary Course Summary Description Our training is technology centric. Although a specific application server product will be used throughout the course, the comprehensive labs and lessons geared towards teaching

More information

Developing Applications with Java EE 6 on WebLogic Server 12c

Developing Applications with Java EE 6 on WebLogic Server 12c Developing Applications with Java EE 6 on WebLogic Server 12c Duration: 5 Days What you will learn The Developing Applications with Java EE 6 on WebLogic Server 12c course teaches you the skills you need

More information

Introduction to Spring Framework: Hibernate, Spring MVC & REST

Introduction to Spring Framework: Hibernate, Spring MVC & REST Introduction to Spring Framework: Hibernate, Spring MVC & REST Training domain: Software Engineering Number of modules: 1 Duration of the training: 36 hours Sofia, 2017 Copyright 2003-2017 IPT Intellectual

More information

Introduction to Spring Framework: Hibernate, Web MVC & REST

Introduction to Spring Framework: Hibernate, Web MVC & REST Introduction to Spring Framework: Hibernate, Web MVC & REST Course domain: Software Engineering Number of modules: 1 Duration of the course: 50 hours Sofia, 2017 Copyright 2003-2017 IPT Intellectual Products

More information

Introduction to Web Application Development Using JEE, Frameworks, Web Services and AJAX

Introduction to Web Application Development Using JEE, Frameworks, Web Services and AJAX Introduction to Web Application Development Using JEE, Frameworks, Web Services and AJAX Duration: 5 Days US Price: $2795 UK Price: 1,995 *Prices are subject to VAT CA Price: CDN$3,275 *Prices are subject

More information

Chapter 1 Introducing EJB 1. What is Java EE Introduction to EJB...5 Need of EJB...6 Types of Enterprise Beans...7

Chapter 1 Introducing EJB 1. What is Java EE Introduction to EJB...5 Need of EJB...6 Types of Enterprise Beans...7 CONTENTS Chapter 1 Introducing EJB 1 What is Java EE 5...2 Java EE 5 Components... 2 Java EE 5 Clients... 4 Java EE 5 Containers...4 Introduction to EJB...5 Need of EJB...6 Types of Enterprise Beans...7

More information

foreword to the first edition preface xxi acknowledgments xxiii about this book xxv about the cover illustration

foreword to the first edition preface xxi acknowledgments xxiii about this book xxv about the cover illustration contents foreword to the first edition preface xxi acknowledgments xxiii about this book xxv about the cover illustration xix xxxii PART 1 GETTING STARTED WITH ORM...1 1 2 Understanding object/relational

More information

Java J Course Outline

Java J Course Outline JAVA EE - J2SE - CORE JAVA After all having a lot number of programming languages. Why JAVA; yet another language!!! AND NOW WHY ONLY JAVA??? CHAPTER 1: INTRODUCTION What is Java? History Versioning The

More information

CO Java EE 7: Back-End Server Application Development

CO Java EE 7: Back-End Server Application Development CO-85116 Java EE 7: Back-End Server Application Development Summary Duration 5 Days Audience Application Developers, Developers, J2EE Developers, Java Developers and System Integrators Level Professional

More information

SPRING MOCK TEST SPRING MOCK TEST I

SPRING MOCK TEST SPRING MOCK TEST I http://www.tutorialspoint.com SPRING MOCK TEST Copyright tutorialspoint.com This section presents you various set of Mock Tests related to Spring Framework. You can download these sample mock tests at

More information

JAVA COURSES. Empowering Innovation. DN InfoTech Pvt. Ltd. H-151, Sector 63, Noida, UP

JAVA COURSES. Empowering Innovation. DN InfoTech Pvt. Ltd. H-151, Sector 63, Noida, UP 2013 Empowering Innovation DN InfoTech Pvt. Ltd. H-151, Sector 63, Noida, UP contact@dninfotech.com www.dninfotech.com 1 JAVA 500: Core JAVA Java Programming Overview Applications Compiler Class Libraries

More information

Call: JSP Spring Hibernate Webservice Course Content:35-40hours Course Outline

Call: JSP Spring Hibernate Webservice Course Content:35-40hours Course Outline JSP Spring Hibernate Webservice Course Content:35-40hours Course Outline Advanced Java Database Programming JDBC overview SQL- Structured Query Language JDBC Programming Concepts Query Execution Scrollable

More information

Table of Contents EJB 3.1 and JPA 2

Table of Contents EJB 3.1 and JPA 2 Table of Contents EJB 3.1 and JPA 2 Enterprise JavaBeans and the Java Persistence API 1 Workshop Overview 2 Workshop Objectives 3 Workshop Agenda 4 Course Prerequisites 5 Labs 6 Session 1: Introduction

More information

Java EE 6: Develop Business Components with JMS & EJBs

Java EE 6: Develop Business Components with JMS & EJBs Oracle University Contact Us: + 38516306373 Java EE 6: Develop Business Components with JMS & EJBs Duration: 4 Days What you will learn This Java EE 6: Develop Business Components with JMS & EJBs training

More information

Oracle - Developing Applications for the Java EE 7 Platform Ed 1 (Training On Demand)

Oracle - Developing Applications for the Java EE 7 Platform Ed 1 (Training On Demand) Oracle - Developing Applications for the Java EE 7 Platform Ed 1 (Training On Demand) Code: URL: D101074GC10 View Online The Developing Applications for the Java EE 7 Platform training teaches you how

More information

Java- EE Web Application Development with Enterprise JavaBeans and Web Services

Java- EE Web Application Development with Enterprise JavaBeans and Web Services Java- EE Web Application Development with Enterprise JavaBeans and Web Services Duration:60 HOURS Price: INR 8000 SAVE NOW! INR 7000 until December 1, 2011 Students Will Learn How to write Session, Message-Driven

More information

Struts: Struts 1.x. Introduction. Enterprise Application

Struts: Struts 1.x. Introduction. Enterprise Application Struts: Introduction Enterprise Application System logical layers a) Presentation layer b) Business processing layer c) Data Storage and access layer System Architecture a) 1-tier Architecture b) 2-tier

More information

object/relational persistence What is persistence? 5

object/relational persistence What is persistence? 5 contents foreword to the revised edition xix foreword to the first edition xxi preface to the revised edition xxiii preface to the first edition xxv acknowledgments xxviii about this book xxix about the

More information

Skyway Builder 6.3 Reference

Skyway Builder 6.3 Reference Skyway Builder 6.3 Reference 6.3.0.0-07/21/09 Skyway Software Skyway Builder 6.3 Reference: 6.3.0.0-07/21/09 Skyway Software Published Copyright 2009 Skyway Software Abstract The most recent version of

More information

JVA-117A. Spring-MVC Web Applications

JVA-117A. Spring-MVC Web Applications JVA-117A. Spring-MVC Web Applications Version 4.2 This course enables the experienced Java developer to use the Spring application framework to manage objects in a lightweight, inversion-of-control container,

More information

Courses For Event Java Advanced Summer Training 2018

Courses For Event Java Advanced Summer Training 2018 Courses For Event Java Advanced Summer Training 2018 Java Fundamentals Oracle Java SE 8 Advanced Java Training Java Advanced Expert Edition Topics For Java Fundamentals Variables Data Types Operators Part

More information

Java Enterprise Edition

Java Enterprise Edition Java Enterprise Edition The Big Problem Enterprise Architecture: Critical, large-scale systems Performance Millions of requests per day Concurrency Thousands of users Transactions Large amounts of data

More information

Enterprise JavaBeans 3.1

Enterprise JavaBeans 3.1 SIXTH EDITION Enterprise JavaBeans 3.1 Andrew Lee Rubinger and Bill Burke O'REILLY* Beijing Cambridge Farnham Kbln Sebastopol Tokyo Table of Contents Preface xv Part I. Why Enterprise JavaBeans? 1. Introduction

More information

Table of Index Hadoop for Developers Hibernate: Using Hibernate For Java Database Access HP FlexNetwork Fundamentals, Rev. 14.21 HP Navigating the Journey to Cloud, Rev. 15.11 HP OneView 1.20 Rev.15.21

More information

Index. setmaxresults() method, 169 sorting, 170 SQL DISTINCT query, 171 uniqueresult() method, 169

Index. setmaxresults() method, 169 sorting, 170 SQL DISTINCT query, 171 uniqueresult() method, 169 Index A Annotations Hibernate mappings, 81, 195 Hibernate-specific persistence annotations Immutable annotation, 109 natural ID, 110 Hibernate XML configuration file, 108 JPA 2 persistence (see JPA 2 persistence

More information

Specialized - Mastering Spring 4.2

Specialized - Mastering Spring 4.2 Specialized - Mastering Spring 4.2 Code: Lengt h: URL: TT3330-S4 5 days View Online The Spring framework is an application framework that provides a lightweight container that supports the creation of

More information

com Spring + Spring-MVC + Spring-Boot + Design Pattern + XML + JMS Hibernate + Struts + Web Services = 8000/-

com Spring + Spring-MVC + Spring-Boot + Design Pattern + XML + JMS Hibernate + Struts + Web Services = 8000/- www.javabykiran. com 8888809416 8888558802 Spring + Spring-MVC + Spring-Boot + Design Pattern + XML + JMS Hibernate + Struts + Web Services = 8000/- Java by Kiran J2EE SYLLABUS Servlet JSP XML Servlet

More information

Java EE Application Assembly & Deployment Packaging Applications, Java EE modules. Model View Controller (MVC)2 Architecture & Packaging EJB Module

Java EE Application Assembly & Deployment Packaging Applications, Java EE modules. Model View Controller (MVC)2 Architecture & Packaging EJB Module Java Platform, Enterprise Edition 5 (Java EE 5) Core Java EE Java EE 5 Platform Overview Java EE Platform Distributed Multi tiered Applications Java EE Web & Business Components Java EE Containers services

More information

Java EE Architecture, Part Three. Java EE architecture, part three 1(57)

Java EE Architecture, Part Three. Java EE architecture, part three 1(57) Java EE Architecture, Part Three Java EE architecture, part three 1(57) Content Requirements on the Integration layer The Database Access Object, DAO Pattern Frameworks for the Integration layer Java EE

More information

Spring Persistence. with Hibernate PAUL TEPPER FISHER BRIAN D. MURPHY

Spring Persistence. with Hibernate PAUL TEPPER FISHER BRIAN D. MURPHY Spring Persistence with Hibernate PAUL TEPPER FISHER BRIAN D. MURPHY About the Authors About the Technical Reviewer Acknowledgments xii xiis xiv Preface xv Chapter 1: Architecting Your Application with

More information

Java EE Architecture, Part Three. Java EE architecture, part three 1(69)

Java EE Architecture, Part Three. Java EE architecture, part three 1(69) Java EE Architecture, Part Three Java EE architecture, part three 1(69) Content Requirements on the Integration layer The Database Access Object, DAO Pattern Frameworks for the Integration layer Java EE

More information

POJOs to the rescue. Easier and faster development with POJOs and lightweight frameworks

POJOs to the rescue. Easier and faster development with POJOs and lightweight frameworks POJOs to the rescue Easier and faster development with POJOs and lightweight frameworks by Chris Richardson cer@acm.org http://chris-richardson.blog-city.com 1 Who am I? Twenty years of software development

More information

Fast Track to EJB 3.0

Fast Track to EJB 3.0 Fast Track to EJB 3.0 using JBoss 4/5 and Eclipse LearningPatterns, Inc. Courseware JBoss is a registered trademark of Red Hat, Inc. in the U.S. and other countries. LearningPatterns has no affiliation

More information

Java EE Architecture, Part Two. Java EE architecture, part two 1

Java EE Architecture, Part Two. Java EE architecture, part two 1 Java EE Architecture, Part Two Java EE architecture, part two 1 Content Requirements on the Business layer Framework Independent Patterns Transactions Frameworks for the Business layer Java EE architecture,

More information

Call: Core&Advanced Java Springframeworks Course Content:35-40hours Course Outline

Call: Core&Advanced Java Springframeworks Course Content:35-40hours Course Outline Core&Advanced Java Springframeworks Course Content:35-40hours Course Outline Object-Oriented Programming (OOP) concepts Introduction Abstraction Encapsulation Inheritance Polymorphism Getting started with

More information

Spring framework was initially written by Rod Johnson and was first released under the Apache 2.0 license in June 2003.

Spring framework was initially written by Rod Johnson and was first released under the Apache 2.0 license in June 2003. About the Tutorial Spring framework is an open source Java platform that provides comprehensive infrastructure support for developing robust Java applications very easily and very rapidly. Spring framework

More information

Business Logic and Spring Framework

Business Logic and Spring Framework Business Logic and Spring Framework Petr Křemen petr.kremen@fel.cvut.cz Winter Term 2017 Petr Křemen (petr.kremen@fel.cvut.cz) Business Logic and Spring Framework Winter Term 2017 1 / 32 Contents 1 Business

More information

Schema Null Cannot Be Resolved For Table Jpa

Schema Null Cannot Be Resolved For Table Jpa Schema Null Cannot Be Resolved For Table Jpa (14, 19) The abstract schema type 'Movie' is unknown. (28, 35) The state field path 'm.title' cannot be resolved to a valid type. at org.springframework.web.servlet.

More information

Shale and the Java Persistence Architecture. Craig McClanahan Gary Van Matre. ApacheCon US 2006 Austin, TX

Shale and the Java Persistence Architecture. Craig McClanahan Gary Van Matre. ApacheCon US 2006 Austin, TX Shale and the Java Persistence Architecture Craig McClanahan Gary Van Matre ApacheCon US 2006 Austin, TX 1 Agenda The Apache Shale Framework Java Persistence Architecture Design Patterns for Combining

More information

Java SE7 Fundamentals

Java SE7 Fundamentals Java SE7 Fundamentals Introducing the Java Technology Relating Java with other languages Showing how to download, install, and configure the Java environment on a Windows system. Describing the various

More information

I Got My Mojo Workin'

I Got My Mojo Workin' I Got My Mojo Workin' Gary Murphy Hilbert Computing, Inc. http://www.hilbertinc.com/ glm@hilbertinc.com Gary Murphy I Got My Mojo Workin' Slide 1 Agenda Quick overview on using Maven 2 Key features and

More information

Enterprise Java Development using JPA, Hibernate and Spring. Srini Penchikala Detroit JUG Developer Day Conference November 14, 2009

Enterprise Java Development using JPA, Hibernate and Spring. Srini Penchikala Detroit JUG Developer Day Conference November 14, 2009 Enterprise Java Development using JPA, Hibernate and Spring Srini Penchikala Detroit JUG Developer Day Conference November 14, 2009 About the Speaker Enterprise Architect Writer, Speaker, Editor (InfoQ)

More information

Lightweight J2EE Framework

Lightweight J2EE Framework Lightweight J2EE Framework Struts, spring, hibernate Software System Design Zhu Hongjun Session 4: Hibernate DAO Refresher in Enterprise Application Architectures Traditional Persistence and Hibernate

More information

Core Capabilities Part 3

Core Capabilities Part 3 2008 coreservlets.com The Spring Framework: Core Capabilities Part 3 Originals of Slides and Source Code for Examples: http://courses.coreservlets.com/course-materials/spring.html Customized Java EE Training:

More information

NetBeans IDE Field Guide

NetBeans IDE Field Guide NetBeans IDE Field Guide Copyright 2005 Sun Microsystems, Inc. All rights reserved. Table of Contents Extending Web Applications with Business Logic: Introducing EJB Components...1 EJB Project type Wizards...2

More information

Socket attaches to a Ratchet. 2) Bridge Decouple an abstraction from its implementation so that the two can vary independently.

Socket attaches to a Ratchet. 2) Bridge Decouple an abstraction from its implementation so that the two can vary independently. Gang of Four Software Design Patterns with examples STRUCTURAL 1) Adapter Convert the interface of a class into another interface clients expect. It lets the classes work together that couldn't otherwise

More information

Developing Spring based WebSphere Portal application using IBM Rational Application Developer

Developing Spring based WebSphere Portal application using IBM Rational Application Developer Developing Spring based WebSphere Portal application using IBM Rational Application Developer Table of Content Abstract...3 Overview...3 Sample Use case...3 Prerequisite :...3 Developing the spring portlet...4

More information

JAVA MICROSERVICES. Java Language Environment. Java Set Up. Java Fundamentals. Packages. Operations

JAVA MICROSERVICES. Java Language Environment. Java Set Up. Java Fundamentals. Packages. Operations Java Language Environment JAVA MICROSERVICES Object Oriented Platform Independent Automatic Memory Management Compiled / Interpreted approach Robust Secure Dynamic Linking MultiThreaded Built-in Networking

More information

Spring Professional v5.0 Exam

Spring Professional v5.0 Exam Spring Professional v5.0 Exam Spring Core Professional v5.0 Dumps Available Here at: /spring-exam/core-professional-v5.0- dumps.html Enrolling now you will get access to 250 questions in a unique set of

More information

Comparative Analysis of EJB3 and Spring Framework

Comparative Analysis of EJB3 and Spring Framework Comparative Analysis of EJB3 and Spring Framework Janis Graudins, Larissa Zaitseva Abstract: The paper describes main facilities of EJB3 and Spring Framework as well as the results of their comparative

More information

DESIGN PATTERN - INTERVIEW QUESTIONS

DESIGN PATTERN - INTERVIEW QUESTIONS DESIGN PATTERN - INTERVIEW QUESTIONS http://www.tutorialspoint.com/design_pattern/design_pattern_interview_questions.htm Copyright tutorialspoint.com Dear readers, these Design Pattern Interview Questions

More information

Module 8 The Java Persistence API

Module 8 The Java Persistence API Module 8 The Java Persistence API Objectives Describe the role of the Java Persistence API (JPA) in a Java EE application Describe the basics of Object Relational Mapping Describe the elements and environment

More information

CORE JAVA. Saying Hello to Java: A primer on Java Programming language

CORE JAVA. Saying Hello to Java: A primer on Java Programming language CORE JAVA Saying Hello to Java: A primer on Java Programming language Intro to Java & its features Why Java very famous? Types of applications that can be developed using Java Writing my first Java program

More information

Introduction to JPA. Fabio Falcinelli

Introduction to JPA. Fabio Falcinelli Introduction to JPA Fabio Falcinelli Me, myself and I Several years experience in active enterprise development I love to design and develop web and standalone applications using Python Java C JavaScript

More information

Holon Platform JPA Datastore Module - Reference manual. Version 5.2.1

Holon Platform JPA Datastore Module - Reference manual. Version 5.2.1 Holon Platform JPA Datastore Module - Reference manual Version 5.2.1 Table of Contents 1. Introduction.............................................................................. 1 1.1. Sources and contributions.............................................................

More information

ADVANCED JAVA COURSE CURRICULUM

ADVANCED JAVA COURSE CURRICULUM ADVANCED JAVA COURSE CURRICULUM Index of Advanced Java Course Content : 1. Basics of Servlet 2. ServletRequest 3. Servlet Collaboration 4. ServletConfig 5. ServletContext 6. Attribute 7. Session Tracking

More information

HIBERNATE MOCK TEST HIBERNATE MOCK TEST IV

HIBERNATE MOCK TEST HIBERNATE MOCK TEST IV http://www.tutorialspoint.com HIBERNATE MOCK TEST Copyright tutorialspoint.com This section presents you various set of Mock Tests related to Hibernate Framework. You can download these sample mock tests

More information

Migrating traditional Java EE applications to mobile

Migrating traditional Java EE applications to mobile Migrating traditional Java EE applications to mobile Serge Pagop Sr. Channel MW Solution Architect, Red Hat spagop@redhat.com Burr Sutter Product Management Director, Red Hat bsutter@redhat.com 2014-04-16

More information

Creating RESTful web services with Spring Boot

Creating RESTful web services with Spring Boot Creating RESTful web services with Spring Boot The Spring framework Free and open source Inversion of Control Container (IoC) Modules DI / AOP Data /Security Web MVC/ REST So much more +++ What is Spring

More information

Spring Framework 2.5: New and Notable. Ben Alex, Principal Software Engineer, SpringSource

Spring Framework 2.5: New and Notable. Ben Alex, Principal Software Engineer, SpringSource Spring Framework 2.5: New and Notable Ben Alex, Principal Software Engineer, SpringSource GOAL> Learn what s new in Spring 2.5 and why it matters to you springsource.com 2 Agenda Goals of Spring 2.5 Support

More information

Specialized - Mastering JEE 7 Web Application Development

Specialized - Mastering JEE 7 Web Application Development Specialized - Mastering JEE 7 Web Application Development Code: Lengt h: URL: TT5100- JEE7 5 days View Online Mastering JEE 7 Web Application Development is a five-day hands-on JEE / Java EE training course

More information

Practice Test. Oracle 1z Java Enterprise Edition 5 Business Component Developer Certified Professional Upgrade Exam. Version: 14.

Practice Test. Oracle 1z Java Enterprise Edition 5 Business Component Developer Certified Professional Upgrade Exam. Version: 14. Oracle 1z0-861 Java Enterprise Edition 5 Business Component Developer Certified Professional Upgrade Exam Practice Test Version: 14.22 QUESTION NO: 1 A developer wants to create a business interface for

More information

COURSE DETAILS: CORE AND ADVANCE JAVA Core Java

COURSE DETAILS: CORE AND ADVANCE JAVA Core Java COURSE DETAILS: CORE AND ADVANCE JAVA Core Java 1. Object Oriented Concept Object Oriented Programming & its Concepts Classes and Objects Aggregation and Composition Static and Dynamic Binding Abstract

More information

MyBatis-Spring Reference Documentation

MyBatis-Spring Reference Documentation MyBatis-Spring 1.0.2 - Reference Documentation The MyBatis Community (MyBatis.org) Copyright 2010 Copies of this document may be made for your own use and for distribution to others, provided that you

More information

Page 1

Page 1 Java 1. Core java a. Core Java Programming Introduction of Java Introduction to Java; features of Java Comparison with C and C++ Download and install JDK/JRE (Environment variables set up) The JDK Directory

More information

Introduction... xv SECTION 1: DEVELOPING DESKTOP APPLICATIONS USING JAVA Chapter 1: Getting Started with Java... 1

Introduction... xv SECTION 1: DEVELOPING DESKTOP APPLICATIONS USING JAVA Chapter 1: Getting Started with Java... 1 Introduction... xv SECTION 1: DEVELOPING DESKTOP APPLICATIONS USING JAVA Chapter 1: Getting Started with Java... 1 Introducing Object Oriented Programming... 2 Explaining OOP concepts... 2 Objects...3

More information

Java SE 8 Fundamentals

Java SE 8 Fundamentals Oracle University Contact Us: +52 1 55 8525 3225 Java SE 8 Fundamentals Duration: 5 Days What you will learn This Java SE 8 Fundamentals training introduces you to object-oriented programming using the

More information

JAVA. 1. Introduction to JAVA

JAVA. 1. Introduction to JAVA JAVA 1. Introduction to JAVA History of Java Difference between Java and other programming languages. Features of Java Working of Java Language Fundamentals o Tokens o Identifiers o Literals o Keywords

More information

JVA-117E. Developing RESTful Services with Spring

JVA-117E. Developing RESTful Services with Spring JVA-117E. Developing RESTful Services with Spring Version 4.1 This course enables the experienced Java developer to use the Spring MVC framework to create RESTful web services. We begin by developing fluency

More information

Leverage Rational Application Developer v8 to develop Java EE6 application and test with WebSphere Application Server v8

Leverage Rational Application Developer v8 to develop Java EE6 application and test with WebSphere Application Server v8 Leverage Rational Application Developer v8 to develop Java EE6 application and test with WebSphere Application Server v8 Author: Ying Liu cdlliuy@cn.ibm.com Date: June 24, 2011 2011 IBM Corporation THE

More information

Spring Framework. Christoph Pickl

Spring Framework. Christoph Pickl Spring Framework Christoph Pickl agenda 1. short introduction 2. basic declaration 3. medieval times 4. advanced features 5. demo short introduction common tool stack Log4j Maven Spring Code Checkstyle

More information

Table of Contents - Fast Track to Hibernate 3

Table of Contents - Fast Track to Hibernate 3 Table of Contents - Fast Track to Hibernate 3 Fast Track to Hibernate 1 Workshop Overview and Objectives 2 Workshop Agenda 3 Release Level 4 Typographic Conventions 5 Labs 6 Session 1: Introduction to

More information

"Web Age Speaks!" Webinar Series

Web Age Speaks! Webinar Series "Web Age Speaks!" Webinar Series Java EE Patterns Revisited WebAgeSolutions.com 1 Introduction Bibhas Bhattacharya CTO bibhas@webagesolutions.com Web Age Solutions Premier provider of Java & Java EE training

More information

The Spring Framework: Overview and Setup

The Spring Framework: Overview and Setup 2009 Marty Hall The Spring Framework: Overview and Setup Originals of Slides and Source Code for Examples: http://courses.coreservlets.com/course-materials/spring.html Customized Java EE Training: http://courses.coreservlets.com/

More information

Chapter 13. Hibernate with Spring

Chapter 13. Hibernate with Spring Chapter 13. Hibernate with Spring What Is Spring? Writing a Data Access Object (DAO) Creating an Application Context Putting It All Together 1 / 24 What is Spring? The Spring Framework is an Inversion

More information

Seam 3. Pete Muir JBoss, a Division of Red Hat

Seam 3. Pete Muir JBoss, a Division of Red Hat Seam 3 Pete Muir JBoss, a Division of Red Hat Road Map Introduction Java EE 6 Java Contexts and Dependency Injection Seam 3 Mission Statement To provide a fully integrated development platform for building

More information

Generating A Hibernate Mapping File And Java Classes From The Sql Schema

Generating A Hibernate Mapping File And Java Classes From The Sql Schema Generating A Hibernate Mapping File And Java Classes From The Sql Schema Internally, hibernate maps from Java classes to database tables (and from It also provides data query and retrieval facilities by

More information

Java Advance Frameworks

Java Advance Frameworks Software Development & Education Center Java Advance Frameworks (Struts Hibernate Spring) STRUTS 2.0 Apache Struts is an open-source framework for creating Java web applications that use the MVC design

More information

/ / JAVA TRAINING

/ / JAVA TRAINING www.tekclasses.com +91-8970005497/+91-7411642061 info@tekclasses.com / contact@tekclasses.com JAVA TRAINING If you are looking for JAVA Training, then Tek Classes is the right place to get the knowledge.

More information

EJB ENTERPRISE JAVA BEANS INTRODUCTION TO ENTERPRISE JAVA BEANS, JAVA'S SERVER SIDE COMPONENT TECHNOLOGY. EJB Enterprise Java

EJB ENTERPRISE JAVA BEANS INTRODUCTION TO ENTERPRISE JAVA BEANS, JAVA'S SERVER SIDE COMPONENT TECHNOLOGY. EJB Enterprise Java EJB Enterprise Java EJB Beans ENTERPRISE JAVA BEANS INTRODUCTION TO ENTERPRISE JAVA BEANS, JAVA'S SERVER SIDE COMPONENT TECHNOLOGY Peter R. Egli 1/23 Contents 1. What is a bean? 2. Why EJB? 3. Evolution

More information