11. Well designed Easy to extend Many reusable classes. Spring substantially reduces code, speeds up development, facilitates easy testing and improves code quality Adlux Consultancy Services Pvt. Ltd.
13. Spring Modules The Core container module AOP module (Aspect Oriented Programming) JDBC abstraction and DAO module O/R mapping integration module (Object/Relational) Web module MVC framework module Adlux Consultancy Services Pvt. Ltd.
14. Inversion of Control (IOC) Instead of objects invoking other objects, the dependant objects are added through an external entity/container. Inversion of Control is the general style of using Dependency Injection to wire the application. Also known as the Hollywood principle – “don’t call me I will call you”. IoC is all about Object dependencies. Prevents hard-coded object creation and object/service lookup. Loose coupling Helps write effective unit tests. Adlux Consultancy Services Pvt. Ltd.
19. Testability is improved because your Objects don't know or care what environment they're in as long as someone injects their dependencies. Hence you can deploy Objects into a test environment and inject Mock Objects for their dependencies with ease.Adlux Consultancy Services Pvt. Ltd.
20. Pull Example public class BookDemoServiceImpl implements BookDemoService { public void addPublisherToBook(Book book) { BookDemoFactory factory = BookDemoFactory.getFactory(); BookDemoDaodao = factory.getBookDemoDao(); String isbn = book.getIsbn(); if (book.getPublisher() == null && isbn != null) { Publisher publisher = dao.findPublisherByIsbn(isbn); book.setPublisher(publisher); } } } Adlux Consultancy Services Pvt. Ltd.
21. Push Example (Dependency Injection) public class BookDemoServiceImpl implements BookDemoService { private BookDemoDaodao; public void addPublisherToBook(Book book) { String isbn = book.getIsbn(); if (book.getPublisher() == null && isbn != null) { Publisher publisher = dao.findPublisherByIsbn(isbn); book.setPublisher(publisher); } } public void setBookDemoDao(BookDemoDaodao) { this.dao = dao; } } Adlux Consultancy Services Pvt. Ltd.
22. Spring IOC The IoC container is the core component of the Spring Framework A bean is an object that is managed by the IoC container The IoC container is responsible for containing and managing beans Spring comes with two types of containers – BeanFactory – ApplicationContext Adlux Consultancy Services Pvt. Ltd.
40. The bean class is the actual implementation of the bean being described by the BeanFactory.
41. Spring will manage the scope of the beans for you. No need for doing it programmaticallyScopes singleton : A single bean definition to a single object instance. Only one shared instance will ever be created by the container The single bean instance will be stored in cache and returned for all requests. Singleton beans are created at container startup-time Singleton is default scope in Spring <bean id=“bean1” class=“Example” scope=“singleton”/> prototype : A new bean instance will be created for each request Use prototype scope for stateful beans – singleton scope for stateless beans <bean id=“bean1” class=“Example” scope=“prototype”/> Adlux Consultancy Services Pvt. Ltd.
42. request Scopes a single bean definition to the lifecycle of a single HTTP request; that is each and every HTTP request will have its own instance of a bean created off the back of a single bean definition. Only valid in the context of a Spring ApplicationContext. session Scopes a single bean definition to the lifecycle of a HTTP Session. Only valid in the context of a Spring ApplicationContext. global session Scopes a single bean definition to the lifecycle of a global HTTP Session. Typically only valid when used in a portlet context. Only valid in the context of a Spring ApplicationContext. request , session , global session scopes are used for spring web applications. Adlux Consultancy Services Pvt. Ltd.
43. Injecting dependencies via constructor Constructor-based DI is effected by invoking a constructor with a number of arguments, each representing a dependency Example of a class that could only be dependency injected using constructor injection. public class BankingAccountImpl{ // the BankingAccountImpl has a dependency on a BankDao Private BankDaobankDao; // a constructor so that the Spring container can 'inject' a BankDao public BankingAccountImpl(BankDaobankDao) { this. bankDao = bankDao; } // business logic that actually 'uses' the injected BankDao object } Adlux Consultancy Services Pvt. Ltd.
44. Injecting dependencies via setter methods Setter-based DI is realized by calling setter methods on your beans after invoking a no-arugument constructor. public class EmployeeRegister { // the EmployeeRegister has a dependency on the Employee private Employee employee; // a setter method so that the Spring container can 'inject' Employee public void setEmployee(Employee employee) { this.employee = employee; } // business logic that actually 'uses' the injected Employee Object } Adlux Consultancy Services Pvt. Ltd.
47. Autowiring Properties Beans may be auto-wired (rather than using <ref>) Per-bean attribute autowire Explicit settings override autowire=“name” Bean identifier matches property name autowire=“type” Type matches other defined bean autowire=”constructor” Match constructor argument types autowire=”autodetect” Attempt by constructor, otherwise “type” Adlux Consultancy Services Pvt. Ltd.
50. Application Layering A clear separation of application component responsibility. - Presentation layer • Concentrates on request/response actions. • Handles UI rendering from a model. • Contains formatting logic and non-business related validation logic. - Persistence layer • Used to communicate with a persistence store such as a relational database. • Provides a query language • Possible O/R mapping capabilities • JDBC, Hibernate, iBATIS, JDO, Entity Beans, etc. - Domain layer • Contains business objects that are used across above layers. • Contain complex relationships between other domain objects. • Domain objects should only have dependencies on other domain objects. Adlux Consultancy Services Pvt. Ltd.
51. What is DAO: J2EE developers use the Data Access Object (DAO) design pattern to separate low-level data access logic from high-level business logic. Implementing the DAO pattern involves more than just writing data access code. DAO stands for data access object, which perfectly describes a DAO’s role in an application. DAOs exist to provide a means to read and write data to the database .They should expose this functionality through an interface by which the rest of the application will access them. Adlux Consultancy Services Pvt. Ltd.
52. Spring’s JDBC API: Why not just use JDBC •Connection management •Exception Handling •Transaction management •Other persistence mechanisms Spring Provides a Consistent JDBC Abstraction • Spring Helper classes •JdbcTemplate • Dao Implementations • Query and BatchQueries Adlux Consultancy Services Pvt. Ltd.
53. Data Access Support for DAO implementations • implicit access to resources • many operations become one-liners • no try/catch blocks anymore Pre-built integration classes • JDBC: JdbcTemplate • Hibernate: HibernateTemplate • JDO: JdoTemplate • TopLink: TopLinkTemplate • iBatis SQL Maps: SqlMapClientTemplate Adlux Consultancy Services Pvt. Ltd.
73. Writing Data: public class InsertAccountStatementCreator implements PreparedStatementCreator { public PreparedStatement createPreparedStatement( Connection conn) throws SQLException { String sql = "insert into abbas_bank_acc(acc_no, acc_holder_name, balance) values (?, ?, ?)"; return conn.prepareStatement(sql); } } Public class InsertAccountStatementSetter implements PreparedStatementSetter{ public void setValues(PreparedStatement ps) throws SQLException { ps.setInt(0, account.getAccno()); ps.setString(1, account.getAcc_holder_name()); ps.setString(2, account.getBalance()); } Adlux Consultancy Services Pvt. Ltd.
74. Reading Data: public class BankAccountRowMapper implements RowMapper { public Object mapRow(ResultSet rs, int index) throws SQLException { BankAccount account = new BankAccount(); account.setAccno(rs.getInt("acc_no")); account.setAcc_holder_name(rs.getString("acc_holder_name")); account.setBalance(rs.getDouble("balance")); } return account; } public List selectAccounts() { String sql = "select * from abbas_bank_acc"; return getJdbcTemplate().query(sql, new BankAccountRowMapper()); } Adlux Consultancy Services Pvt. Ltd.
75. JDBC Template Methods: execute(String sql) : Issue a single SQL execute, typically a DDL statement. execute(CallableStatementCreator csc,CallableStatementCa llback action) : Execute a JDBC data access operation, implemented as callback action working on a JDBC CallableStatement. execute(PrepatedStatementCreator csc,PreparedStatementCa llback action) : Execute a JDBC data access operation, implemented as callback action working on a JDBC PreparedStatement. Adlux Consultancy Services Pvt. Ltd.
76. JDBC Template Methods: query(String sql, Object[] args, int[] argTypes, RowCallbackHandler rch) : Query given SQL to create a prepared statement from SQL and a list of arguments to bind to the query, reading the ResultSet on a per-row basis with a RowCallbackHandler. query(String sql, Object[] args, int[] argTypes, RowMapper rowMapper) : Query given SQL to create a prepared statement from SQL and a list of arguments to bind to the query, mapping each row to a Java object via a RowMapper. update(String sql, Object[] args) : Issue a single SQL update operation (such as an insert, update or delete statement) via a prepared statement, binding the given arguments. Adlux Consultancy Services Pvt. Ltd.
77. Example for a JDBC-based DAO public class BankDaoImpl extends JdbcDaoSupport implements BankDAO { public void createAccount(BankAccount account) { getJdbcTemplate().execute(“insert into bank_acc values(“+accno+”,”+name+”,”+balance+”)”); } public void deleteAccount(int accno) { String sql = "delete from abbas_bank_acc where acc_no=?"; getJdbcTemplate().update(sql,new Object[]{new Integer(accno)}); } public BankAccount selectAccount(int accno) { String sql = "select * from bank_acc where acc_no=?"; final BankAccount account = new BankAccount(); getJdbcTemplate().query(sql,new Object[]{accno},new RowCallbackHandler(){ public void processRow(ResultSet rs) throws SQLException { account.setAccno(rs.getInt("acc_no")); account.setAcc_holder_name(rs.getString("acc_holder_name")); account.setBalance(rs.getDouble("balance")); } }); return account; } public List selectAccounts() { String sql = "select * from bank_acc"; return getJdbcTemplate().queryForList("select * from bank_acc where accno="+accno); public void updateAccount(BankAccount account) { String sql = "update bank_acc set balance=? where acc_no=?"; getJdbcTemplate().update(sql, new Object[]{account.getBalance(),account.getAccno()}); }}
104. Configuring Springs’ Hibernate Template <bean id="hibernateTemplate" class="org.springframework.orm.hibernate.HibernateTemplate"> <property name="sessionFactory"> <ref bean="sessionFactory"/> </property> </bean> <bean id="studentDao" class="com.adlux..dao.hibernate.StudentDaoHibernate"> <property name="hibernateTemplate"> <ref bean="hibernateTemplate"/> </property> </bean> <bean id="courseDao" class="com.adlux. dao.hibernate.CourseDaoHibernate"> <property name="hibernateTemplate"> <ref bean="hibernateTemplate"/> </property> </bean> Configuring a HibernateTemplate class Wiring Template class with multiple DAO objects. Adlux Consultancy Services Pvt. Ltd.
105. Hibernate Template Spring framework provides template class for Hibernate framework, which helps release the programmer from writing some repetitive codes. This template class is called HibernateTemplate. Using HibernateTemplate and HibernateCallback public Student getStudent(final Integer id) { return (Student) hibernateTemplate.execute( new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException { return session.load(Student.class, id); } }); } Adlux Consultancy Services Pvt. Ltd.
106.
107. Hibernate Template Methods hibernate.load(Class entityClass, Serializable id) Return the persistent instance of the given entity class with the given identifier, throwing an exception if not found. hibernate.save(Object entity) Persist the given transient instance. hibernate.update(Object entity) Update the given persistent instance, associating it with the current Hibernate Session. Adlux Consultancy Services Pvt. Ltd.
108. Examples Using HibernateTemplate List employees = hibernatetemplate.find("from Credit"); List list = hibernatetemplate.find("from Credit c where c.cardtype=?", “Master card”); Save Credit c = new Credit(5121212121212124, ”Master card”,……); hibernatetemplate.save(c); Load & Update Credit e = (Employee) hibernatetemplate.load(Credit.class, cardno); c.setFirstName(“Anusha"); hibernatetemplate.update(e); Adlux Consultancy Services Pvt. Ltd.
113. We can make our DAO class extends HibernateDaoSupport instead of injecting the instance of HibernateTemplate to each DAO class.
114. Also provides many other methods like getSession() , closeSessionIfNecessary()Adlux Consultancy Services Pvt. Ltd.
115. Example for Spring Dao extending HibernateDaoSupport public class ExampleHibernateDAO extends HibernateDaoSupport { public void insertEmployee(Employee emp) { getHibernateTemplate().save(emp); } public List getAllEmployees() { return getHibernateTemplate().find("from Employee"); } public List findEmployeebyName(String ename) { return getHibernateTemplate().find("from Employee emp where emp.firstname=?", ename); } public void deleteEmployee(String empid) { getHibernateTemplate().delete(getHibernateTemplate().load( Employee.class, empid)); } public void updateEmployee(String empid) { Employee e = (Employee) getHibernateTemplate().load( Employee.class, empid); e.setFirstname("Anusha"); getHibernateTemplate().update(e); } } Adlux Consultancy Services Pvt. Ltd.
116. WriningsessionFactory to our DAO class <bean id="ExampleDao" class=“com.adlux.dao.ExampleHibernateDao"> <property name="sessionFactory"> <ref bean="sessionFactory"/> </property> </bean> Adlux Consultancy Services Pvt. Ltd.
117. Examples using HibernateTemplate and plain hibernate Hibernate Only : public User getUserByEmailAddress(final String email) { try { Session session =getsessionFactory().openSession(); List list = session.find( "from User user where user.email=‘”+ email+”’”); return (User) list.get(0); } Catch (Exception e){ e.printstackTrace(); } finally {session.close(); } } Hibernate Template : public User getUserByEmailAddress(final String email) { List list = getHibernateTemplate().find( "from User user where user.email=?”, email); return (User) list.get(0); } Adlux Consultancy Services Pvt. Ltd.
118. Consistent exception hierarchy in spring Spring provides a convenient translation from technology specific exceptions like SQLException and HibernateException to its own exception hierarchy with the DataAccessException as the root exception. DataAccessException is a RuntimeException, so it is an unchecked exception. Our code will not be required to handle these exceptions when they are thrown by the data access tier. DataAccessException is the root of all Spring DAO exceptions Adlux Consultancy Services Pvt. Ltd.