Author:GoalKicker.com
No description
Tags
Support Statistics
¥.00 ·
0times
Text Preview (First 20 pages)
Registered users can read the full content for free
Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.
Page
1
Spring Framework Notes for ProfessionalsSpring® Framework Notes for Professionals GoalKicker.com Free Programming Books Disclaimer This is an unocial free book created for educational purposes and is not aliated with ocial Spring® Framework group(s) or company(s). All trademarks and registered trademarks are the property of their respective owners 50+ pages of professional hints and tricks
Page
2
Contents About 1 ................................................................................................................................................................................... Chapter 1: Getting started with Spring Framework 2 .................................................................................... Section 1.1: Setup (XML Configuration) 2 ........................................................................................................................ Section 1.2: Showcasing Core Spring Features by example 3 ..................................................................................... Section 1.3: What is Spring Framework, why should we go for it? 6 ........................................................................... Chapter 2: Spring Core 8 ............................................................................................................................................... Section 2.1: Introduction to Spring Core 8 ...................................................................................................................... Section 2.2: Understanding How Spring Manage Dependency? 9 ............................................................................. Chapter 3: Spring Expression Language (SpEL) 12 ......................................................................................... Section 3.1: Syntax Reference 12 .................................................................................................................................... Chapter 4: Obtaining a SqlRowSet from SimpleJdbcCall 13 ..................................................................... Section 4.1: SimpleJdbcCall creation 13 ......................................................................................................................... Section 4.2: Oracle Databases 14 ................................................................................................................................... Chapter 5: Creating and using beans 16 .............................................................................................................. Section 5.1: Autowiring all beans of a specific type 16 ................................................................................................. Section 5.2: Basic annotation autowiring 17 ................................................................................................................. Section 5.3: Using FactoryBean for dynamic bean instantiation 18 ........................................................................... Section 5.4: Declaring Bean 19 ....................................................................................................................................... Section 5.5: Autowiring specific bean instances with @Qualifier 20 ........................................................................... Section 5.6: Autowiring specific instances of classes using generic type parameters 21 ........................................ Section 5.7: Inject prototype-scoped beans into singletons 22 ................................................................................... Chapter 6: Bean scopes 25 ........................................................................................................................................... Section 6.1: Additional scopes in web-aware contexts 25 ............................................................................................ Section 6.2: Prototype scope 26 ..................................................................................................................................... Section 6.3: Singleton scope 28 ....................................................................................................................................... Chapter 7: Conditional bean registration in Spring 30 .................................................................................. Section 7.1: Register beans only when a property or value is specified 30 ................................................................ Section 7.2: Condition annotations 30 ............................................................................................................................ Chapter 8: Spring JSR 303 Bean Validation 32 .................................................................................................. Section 8.1: @Valid usage to validate nested POJOs 32 .............................................................................................. Section 8.2: Spring JSR 303 Validation - Customize error messages 32 ................................................................... Section 8.3: JSR303 Annotation based validations in Springs examples 34 .............................................................. Chapter 9: ApplicationContext Configuration 37 .............................................................................................. Section 9.1: Autowiring 37 ................................................................................................................................................ Section 9.2: Bootstrapping the ApplicationContext 37 ................................................................................................. Section 9.3: Java Configuration 38 ................................................................................................................................. Section 9.4: Xml Configuration 40 ................................................................................................................................... Chapter 10: RestTemplate 43 ..................................................................................................................................... Section 10.1: Downloading a Large File 43 ..................................................................................................................... Section 10.2: Setting headers on Spring RestTemplate request 43 ............................................................................ Section 10.3: Generics results from Spring RestTemplate 44 ...................................................................................... Section 10.4: Using Preemptive Basic Authentication with RestTemplate and HttpClient 44 .................................. Section 10.5: Using Basic Authentication with HttpComponent's HttpClient 46 ......................................................... Chapter 11: Task Execution and Scheduling 47 .................................................................................................. Section 11.1: Enable Scheduling 47 ................................................................................................................................... Section 11.2: Cron expression 47 ......................................................................................................................................
Page
3
Section 11.3: Fixed delay 49 .............................................................................................................................................. Section 11.4: Fixed Rate 49 ............................................................................................................................................... Chapter 12: Spring Lazy Initialization 50 ............................................................................................................... Section 12.1: Example of Lazy Init in Spring 50 .............................................................................................................. Section 12.2: For component scanning and auto-wiring 51 ......................................................................................... Section 12.3: Lazy initialization in the configuration class 51 ....................................................................................... Chapter 13: Property Source 52 ................................................................................................................................. Section 13.1: Sample xml configuration using PropertyPlaceholderConfigurer 52 .................................................... Section 13.2: Annotation 52 .............................................................................................................................................. Chapter 14: Dependency Injection (DI) and Inversion of Control (IoC) 53 ........................................... Section 14.1: Autowiring a dependency through Java configuration 53 ..................................................................... Section 14.2: Autowiring a dependency through XML configuration 53 ..................................................................... Section 14.3: Injecting a dependency manually through XML configuration 54 ........................................................ Section 14.4: Injecting a dependency manually through Java configuration 56 ...................................................... Chapter 15: JdbcTemplate 57 ..................................................................................................................................... Section 15.1: Basic Query methods 57 ............................................................................................................................ Section 15.2: Query for List of Maps 57 .......................................................................................................................... Section 15.3: SQLRowSet 58 ............................................................................................................................................. Section 15.4: Batch operations 58 ................................................................................................................................... Section 15.5: NamedParameterJdbcTemplate extension of JdbcTemplate 59 ........................................................ Chapter 16: SOAP WS Consumption 60 ................................................................................................................... Section 16.1: Consuming a SOAP WS with Basic auth 60 .............................................................................................. Chapter 17: Spring profile 61 ....................................................................................................................................... Section 17.1: Spring Profiles allows to configure parts available for certain environment 61 .................................. Chapter 18: Understanding the dispatcher-servlet.xml 62 .......................................................................... Section 18.1: dispatcher-servlet.xml 62 ........................................................................................................................... Section 18.2: dispatcher servlet configuration in web.xml 62 ....................................................................................... Credits 64 .............................................................................................................................................................................. You may also like 65 ........................................................................................................................................................
Page
4
GoalKicker.com – Spring® Framework Notes for Professionals 1 About Please feel free to share this PDF with anyone for free, latest version of this book can be downloaded from: https://goalkicker.com/SpringFrameworkBook This Spring® Framework Notes for Professionals book is compiled from Stack Overflow Documentation, the content is written by the beautiful people at Stack Overflow. Text content is released under Creative Commons BY-SA, see credits at the end of this book whom contributed to the various chapters. Images may be copyright of their respective owners unless otherwise specified This is an unofficial free book created for educational purposes and is not affiliated with official Spring® Framework group(s) or company(s) nor Stack Overflow. All trademarks and registered trademarks are the property of their respective company owners The information presented in this book is not guaranteed to be correct nor accurate, use at your own risk Please send feedback and corrections to web@petercv.com
Page
5
GoalKicker.com – Spring® Framework Notes for Professionals 2 Chapter 1: Getting started with Spring Framework Version Release Date 5.0.x 2017-10-24 4.3.x 2016-06-10 4.2.x 2015-07-31 4.1.x 2014-09-14 4.0.x 2013-12-12 3.2.x 2012-12-13 3.1.x 2011-12-13 3.0.x 2009-12-17 2.5.x 2007-12-25 2.0.x 2006-10-04 1.2.x 2005-05-13 1.1.x 2004-09-05 1.0.x 2003-03-24 Section 1.1: Setup (XML Configuration) Steps to create Hello Spring: Investigate Spring Boot to see if that would better suit your needs.1. Have a project set up with the correct dependencies. It is recommended that you are using Maven or Gradle.2. create a POJO class, e.g. Employee.java3. create a XML file where you can define your class and variables. e.g beans.xml4. create your main class e.g. Customer.java5. Include spring-beans (and its transitive dependencies!) as a dependency.6. Employee.java: package com.test; public class Employee { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } public void displayName() { System.out.println(name); } } beans.xml:
Page
6
GoalKicker.com – Spring® Framework Notes for Professionals 3 <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd"> <bean id="employee" class="com.test.Employee"> <property name="name" value="test spring"></property> </bean> </beans> Customer.java: package com.test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Customer { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml"); Employee obj = (Employee) context.getBean("employee"); obj.displayName(); } } Section 1.2: Showcasing Core Spring Features by example Description This is a self-contained running example including/showcasing: minimum dependencies needed, Java Configuration, Bean declaration by annotation and Java Configuration, Dependency Injection by Constructor and by Property, and Pre/Post hooks. Dependencies These dependencies are needed in the classpath: spring-core1. spring-context2. spring-beans3. spring-aop4. spring-expression5. commons-logging6. Main Class Starting from the end, this is our Main class that serves as a placeholder for the main() method which initialises the Application Context by pointing to the Configuration class and loads all the various beans needed to showcase particular functionality. package com.stackoverflow.documentation; import org.springframework.context.ApplicationContext;
Page
7
GoalKicker.com – Spring® Framework Notes for Professionals 4 import org.springframework.context.annotation.AnnotationConfigApplicationContext; public class Main { public static void main(String[] args) { //initializing the Application Context once per application. ApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfig.class); //bean registered by annotation BeanDeclaredByAnnotation beanDeclaredByAnnotation = applicationContext.getBean(BeanDeclaredByAnnotation.class); beanDeclaredByAnnotation.sayHello(); //bean registered by Java configuration file BeanDeclaredInAppConfig beanDeclaredInAppConfig = applicationContext.getBean(BeanDeclaredInAppConfig.class); beanDeclaredInAppConfig.sayHello(); //showcasing constructor injection BeanConstructorInjection beanConstructorInjection = applicationContext.getBean(BeanConstructorInjection.class); beanConstructorInjection.sayHello(); //showcasing property injection BeanPropertyInjection beanPropertyInjection = applicationContext.getBean(BeanPropertyInjection.class); beanPropertyInjection.sayHello(); //showcasing PreConstruct / PostDestroy hooks BeanPostConstructPreDestroy beanPostConstructPreDestroy = applicationContext.getBean(BeanPostConstructPreDestroy.class); beanPostConstructPreDestroy.sayHello(); } } Application Configuration file The configuration class is annotated by @Configuration and is used as a parameter in the initialised Application Context. The @ComponentScan annotation at the class level of the configuration class points to a package to be scanned for Beans and dependencies registered using annotations. Finally the @Bean annotation serves as a bean definition in the configuration class. package com.stackoverflow.documentation; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @Configuration @ComponentScan("com.stackoverflow.documentation") public class AppConfig { @Bean public BeanDeclaredInAppConfig beanDeclaredInAppConfig() { return new BeanDeclaredInAppConfig(); }
Page
8
GoalKicker.com – Spring® Framework Notes for Professionals 5 } Bean Declaration by Annotation The @Component annotation serves to demarcate the POJO as a Spring bean available for registration during component scanning. @Component public class BeanDeclaredByAnnotation { public void sayHello() { System.out.println("Hello, World from BeanDeclaredByAnnotation !"); } } Bean Declaration by Application Configuration Notice that we don't need to annotate or otherwise mark our POJO since the bean declaration/definition is happening in the Application Configuration class file. public class BeanDeclaredInAppConfig { public void sayHello() { System.out.println("Hello, World from BeanDeclaredInAppConfig !"); } } Constructor Injection Notice that the @Autowired annotation is set at the constructor level. Also notice that unless explicitely defined by name the default autowiring is happening based on the type of the bean (in this instance BeanToBeInjected). package com.stackoverflow.documentation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class BeanConstructorInjection { private BeanToBeInjected dependency; @Autowired public BeanConstructorInjection(BeanToBeInjected dependency) { this.dependency = dependency; } public void sayHello() { System.out.print("Hello, World from BeanConstructorInjection with dependency: "); dependency.sayHello(); } } Property Injection Notice that the @Autowired annotation demarcates the setter method whose name follows the JavaBeans standard.
Page
9
GoalKicker.com – Spring® Framework Notes for Professionals 6 package com.stackoverflow.documentation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class BeanPropertyInjection { private BeanToBeInjected dependency; @Autowired public void setBeanToBeInjected(BeanToBeInjected beanToBeInjected) { this.dependency = beanToBeInjected; } public void sayHello() { System.out.println("Hello, World from BeanPropertyInjection !"); } } PostConstruct / PreDestroy hooks We can intercept initialisation and destruction of a Bean by the @PostConstruct and @PreDestroy hooks. package com.stackoverflow.documentation; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; @Component public class BeanPostConstructPreDestroy { @PostConstruct public void pre() { System.out.println("BeanPostConstructPreDestroy - PostConstruct"); } public void sayHello() { System.out.println(" Hello World, BeanPostConstructPreDestroy !"); } @PreDestroy public void post() { System.out.println("BeanPostConstructPreDestroy - PreDestroy"); } } Section 1.3: What is Spring Framework, why should we go for it? Spring is a framework, which provides bunch of classes, by using this we don't need to write boiler plate logic in our code, so Spring provides an abstract layer on J2ee. For Example in Simple JDBC Application programmer is responsible for Loading the driver class1.
Page
10
GoalKicker.com – Spring® Framework Notes for Professionals 7 Creating the connection2. Creating statement object3. Handling the exceptions4. Creating query5. Executing query6. Closing the connection7. Which is treated as boilerplate code as every programmer write the same code. So for simplicity the framework takes care of boilerplate logic and the programmer has to write only business logic. So by using Spring framework we can develop projects rapidly with minimum lines of code, without any bug, the development cost and time also reduced. So Why to choose Spring as struts is there Strut is a framework which provide solution to web aspects only and struts is invasive in nature. Spring has many features over struts so we have to choose Spring. Spring is Noninvasive in nature: That means you don't need to extend any classes or implement any1. interfaces to your class. Spring is versatile: That means it can integrated with any existing technology in your project.2. Spring provides end to end project development: That means we can develop all the modules like business3. layer, persistence layer. Spring is light weight: That means if you want to work on particular module then , you don't need to learn4. complete spring, only learn that particular module(eg. Spring Jdbc, Spring DAO) Spring supports dependency injection.5. Spring supports multiple project development eg: Core java Application, Web Application, Distributed6. Application, Enterprise Application. Spring supports Aspect oriented Programming for cross cutting concerns.7. So finally we can say Spring is an alternative to Struts. But Spring is not a replacement of J2EE API, As Spring supplied classes internally uses J2EE API classes. Spring is a vast framework so it has divided into several modules. No module is dependent to another except Spring Core. Some Important modules are Spring Core1. Spring JDBC2. Spring AOP3. Spring Transaction4. Spring ORM5. Spring MVC6.
Page
11
GoalKicker.com – Spring® Framework Notes for Professionals 8 Chapter 2: Spring Core Section 2.1: Introduction to Spring Core Spring is a vast framework, so the Spring framework has been divided in several modules which makes spring lightweight. Some important modules are: Spring Core1. Spring AOP2. Spring JDBC3. Spring Transaction4. Spring ORM5. Spring MVC6. All the modules of Spring are independent of each other except Spring Core. As Spring core is the base module, so in all module we have to use Spring Core Spring Core Spring Core talking all about dependency management.That means if any arbitrary classes provided to spring then Spring can manage dependency. What is a dependency: From project point of view, in a project or application multiple classes are there with different functionality. and each classes required some functionality of other classes. Example: class Engine { public void start() { System.out.println("Engine started"); } } class Car { public void move() { // For moving start() method of engine class is required } } Here class Engine is required by class car so we can say class engine is dependent to class Car, So instead of we managing those dependency by Inheritance or creating object as fallows. By Inheritance: class Engine { public void start() { System.out.println("Engine started"); } } class Car extends Engine {
Page
12
GoalKicker.com – Spring® Framework Notes for Professionals 9 public void move() { start(); //Calling super class start method, } } By creating object of dependent class: class Engine { public void start() { System.out.println("Engine started"); } } class Car { Engine eng = new Engine(); public void move() { eng.start(); } } So instead of we managing dependency between classes spring core takes the responsibility dependency management. But Some rule are there, The classes must be designed with some design technique that is Strategy design pattern. Section 2.2: Understanding How Spring Manage Dependency? Let me write a piece of code which shows completely loosely coupled, Then you can easily understand how Spring core manage the dependency internally. Consider an scenario, Online business Flipkart is there, it uses some times DTDC or Blue Dart courier service , So let me design a application which shows complete loosely coupled. The Eclipse Directory as fallows: //Interface package com.sdp.component; public interface Courier { public String deliver(String iteams,String address); }
Page
13
GoalKicker.com – Spring® Framework Notes for Professionals 10 //implementation classes package com.sdp.component; public class BlueDart implements Courier { public String deliver(String iteams, String address) { return iteams+ "Shiped to Address "+address +"Through BlueDart"; } } package com.sdp.component; public class Dtdc implements Courier { public String deliver(String iteams, String address) { return iteams+ "Shiped to Address "+address +"Through Dtdc"; } } //Component classe package com.sdp.service; import com.sdp.component.Courier; public class FlipKart { private Courier courier; public void setCourier(Courier courier) { this.courier = courier; } public void shopping(String iteams,String address) { String status=courier.deliver(iteams, address); System.out.println(status); } } //Factory classes to create and return Object package com.sdp.util; import java.io.IOException; import java.util.Properties; import com.sdp.component.Courier; public class ObjectFactory { private static Properties props; static{ props=new Properties(); try {
Page
14
GoalKicker.com – Spring® Framework Notes for Professionals 11 props.load(ObjectFactory.class.getClassLoader().getResourceAsStream("com//sdp//common//app.properti es")); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static Object getInstance(String logicalclassName) { Object obj = null; String originalclassName=props.getProperty(logicalclassName); try { obj=Class.forName(originalclassName).newInstance(); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } return obj; } } //properties file BlueDart.class=com.sdp.component.BlueDart Dtdc.class=com.sdp.component.Dtdc FlipKart.class=com.sdp.service.FlipKart //Test class package com.sdp.test; import com.sdp.component.Courier; import com.sdp.service.FlipKart; import com.sdp.util.ObjectFactory; public class FlipKartTest { public static void main(String[] args) { Courier courier=(Courier)ObjectFactory.getInstance("Dtdc.class"); FlipKart flipkart=(FlipKart)ObjectFactory.getInstance("FlipKart.class"); flipkart.setCourier(courier); flipkart.shopping("Hp Laptop", "SR Nagar,Hyderabad"); } } If we write this code then we can manually achieve loose coupling,this is applicable if all the classes want either BlueDart or Dtdc , But if some class want BlueDart and some other class want Dtdc then again it will be tightly coupled, So instead of we creating and managing the dependency injection Spring core takes the responsibility of creating and managing the beans, Hope This will helpful, in next example we wil see the !st application on Spring core with deitals
Page
15
GoalKicker.com – Spring® Framework Notes for Professionals 12 Chapter 3: Spring Expression Language (SpEL) Section 3.1: Syntax Reference You can use @Value("#{expression}") to inject value at runtime, in which the expression is a SpEL expression. Literal expressions Supported types include strings, dates, numeric values (int, real, and hex), boolean and null. "#{'Hello World'}" //strings "#{3.1415926}" //numeric values (double) "#{true}" //boolean "#{null}" //null Inline list "#{1,2,3,4}" //list of number "#{{'a','b'},{'x','y'}}" //list of list Inline Maps "#{name:'Nikola',dob:'10-July-1856'}" "#{name:{first:'Nikola',last:'Tesla'},dob:{day:10,month:'July',year:1856}}" //map of maps Invoking Methods "#{'abc'.length()}" //evaluates to 3 "#{f('hello')}" //f is a method in the class to which this expression belongs, it has a string parameter
Page
16
GoalKicker.com – Spring® Framework Notes for Professionals 13 Chapter 4: Obtaining a SqlRowSet from SimpleJdbcCall This describes how to directly obtain a SqlRowSet using SimpleJdbcCall with a stored procedure in your database that has a cursor output parameter, I am working with an Oracle database, I've attempted to create an example that should work for other databases, my Oracle example details issues with Oracle. Section 4.1: SimpleJdbcCall creation Typically, you will want to create your SimpleJdbcCalls in a Service. This example assumes your procedure has a single output parameter that is a cursor; you will need to adjust your declareParameters to match your procedure. @Service public class MyService() { @Autowired private DataSource dataSource; // Autowire your configuration, for example @Value("${db.procedure.schema}") String schema; private SimpleJdbcCall myProcCall; // create SimpleJdbcCall after properties are configured @PostConstruct void initialize() { this.myProcCall = new SimpleJdbcCall(dataSource) .withProcedureName("my_procedure_name") .withCatalogName("my_package") .withSchemaName(schema) .declareParameters(new SqlOutParameter( "out_param_name", Types.REF_CURSOR, new SqlRowSetResultSetExtractor())); } public SqlRowSet myProc() { Map<String, Object> out = this.myProcCall.execute(); return (SqlRowSet) out.get("out_param_name"); } } There are many options you can use here: withoutProcedureColumnMetaDataAccess() needed if you have overloaded procedure names or just don't want SimpleJdbcCall to validate against the database. withReturnValue() if procedure has a return value. First value given to declareParameters defines the return value. Also, if your procedure is a function, use withFunctionName and executeFunction when executing. withNamedBinding() if you want to give arguments using names instead of position.
Page
17
GoalKicker.com – Spring® Framework Notes for Professionals 14 useInParameterNames() defines the argument order. I think this may be required if you pass in your arguments as a list instead of a map of argument name to value. Though it may only be required if you use withoutProcedureColumnMetaDataAccess() Section 4.2: Oracle Databases Here's how to resolve issues with Oracle. Assuming your procedure output parameter is ref cursor, you will get this exception. java.sql.SQLException: Invalid column type: 2012 So change Types.REF_CURSOR to OracleTypes.CURSOR in simpleJdbcCall.declareParameters() Supporting OracleTypes You may only need to do this if you have certain column types in your data. The next issue I encountered was that proprietary Types such as oracle.sql.TIMESTAMPTZ caused this error in SqlRowSetResultSetExtractor: Invalid SQL type for column; nested exception is java.sql.SQLException: Invalid SQL type for column So we need to create a ResultSetExtractor that supports Oracle types. I will explain the reason for password after this code. package com.boost.oracle; import oracle.jdbc.rowset.OracleCachedRowSet; import org.springframework.dao.DataAccessException; import org.springframework.jdbc.core.ResultSetExtractor; import org.springframework.jdbc.support.rowset.ResultSetWrappingSqlRowSet; import org.springframework.jdbc.support.rowset.SqlRowSet; import java.sql.ResultSet; import java.sql.SQLException; /** * OracleTypes can cause {@link org.springframework.jdbc.core.SqlRowSetResultSetExtractor} * to fail due to a Oracle SQL type that is not in the standard {@link java.sql.Types}. * * Also, types such as {@link oracle.sql.TIMESTAMPTZ} require a Connection when processing * the ResultSet; {@link OracleCachedRowSet#getConnectionInternal()} requires a JNDI * DataSource name or the username and password to be set. * * For now I decided to just set the password since changing SpringBoot to a JNDI DataSource * configuration is a bit complicated. * * Created by Arlo White on 2/23/17. */ public class OracleSqlRowSetResultSetExtractor implements ResultSetExtractor<SqlRowSet> { private String oraclePassword; public OracleSqlRowSetResultSetExtractor(String oraclePassword) {
Page
18
GoalKicker.com – Spring® Framework Notes for Professionals 15 this.oraclePassword = oraclePassword; } @Override public SqlRowSet extractData(ResultSet rs) throws SQLException, DataAccessException { OracleCachedRowSet cachedRowSet = new OracleCachedRowSet(); // allows getConnectionInternal to get a Connection for TIMESTAMPTZ cachedRowSet.setPassword(oraclePassword); cachedRowSet.populate(rs); return new ResultSetWrappingSqlRowSet(cachedRowSet); } } Certain Oracle types require a Connection to obtain the column value from a ResultSet. TIMESTAMPTZ is one of these types. So when rowSet.getTimestamp(colIndex) is called, you will get this exception: Caused by: java.sql.SQLException: One or more of the authenticating RowSet properties not set at oracle.jdbc.rowset.OracleCachedRowSet.getConnectionInternal(OracleCachedRowSet.java:560) at oracle.jdbc.rowset.OracleCachedRowSet.getTimestamp(OracleCachedRowSet.java:3717) at org.springframework.jdbc.support.rowset.ResultSetWrappingSqlRowSet.getTimestamp If you dig into this code, you will see that the OracleCachedRowSet needs the password or a JNDI DataSource name to get a Connection. If you prefer the JNDI lookup, just verify that OracleCachedRowSet has DataSourceName set. So in my Service, I Autowire in the password and declare the output parameter like this: new SqlOutParameter("cursor_param_name", OracleTypes.CURSOR, new OracleSqlRowSetResultSetExtractor(oraclePassword))
Page
19
GoalKicker.com – Spring® Framework Notes for Professionals 16 Chapter 5: Creating and using beans Section 5.1: Autowiring all beans of a specific type If you've got multiple implementations of the same interface, Spring can autowire them all into a collection object. I'm going to use an example using a Validator pattern1 Foo Class: public class Foo { private String name; private String emailAddress; private String errorMessage; /** Getters & Setters omitted **/ } Interface: public interface FooValidator { public Foo validate(Foo foo); } Name Validator Class: @Component(value="FooNameValidator") public class FooNameValidator implements FooValidator { @Override public Foo validate(Foo foo) { //Validation logic goes here. } } Email Validator Class: @Component(value="FooEmailValidator") public class FooEmailValidator implements FooValidator { @Override public Foo validate(Foo foo) { //Different validation logic goes here. } } You can now autowire these validators individually or together into a class. Interface: public interface FooService { public void handleFoo(Foo foo); } Class: @Service public class FooServiceImpl implements FooService { /** Autowire all classes implementing FooValidator interface**/ @Autowired
Page
20
GoalKicker.com – Spring® Framework Notes for Professionals 17 private List<FooValidator> allValidators; @Override public void handleFoo(Foo foo) { /**You can use all instances from the list**/ for(FooValidator validator : allValidators) { foo = validator.validate(foo); } } } It's worth noting that if you have more than one implementation of an interface in the Spring IoC container and don't specify which one you want to use with the @Qualifier annotation, Spring will throw an exception when trying to start, because it won't know which instance to use. 1: This is not the right way to do such simple validations. This is a simple example about autowiring. If you want an idea of a much easier validation method look up how Spring does validation with annotations. Section 5.2: Basic annotation autowiring Interface: public interface FooService { public int doSomething(); } Class: @Service public class FooServiceImpl implements FooService { @Override public int doSomething() { //Do some stuff here return 0; } } It should be noted that a class must implement an interface for Spring to be able to autowire this class. There is a method to allow Spring to autowire stand-alone classes using load time weaving, but that is out of scope for this example. You can gain access to this bean in any class that instantiated by the Spring IoC container using the @Autowired annotation. Usage: @Autowired([required=true]) The @Autowired annotation will first attempt to autowire by type, and then fall back on bean name in the event of ambiguity. This annotation can be applied in several different ways. Constructor injection: public class BarClass() { private FooService fooService
Comments 0
Loading comments...
Reply to Comment
Edit Comment