Presentation is loading. Please wait.

Presentation is loading. Please wait.

Unit-2 Beans and Containers.

Similar presentations


Presentation on theme: "Unit-2 Beans and Containers."— Presentation transcript:

1 Unit-2 Beans and Containers

2 Factory Pattern

3 Spring Container In a Spring-based application, your application objects will live within the Spring container. the container will create the objects, wire them together, configure them, and manage their complete lifecycle from the instance the new() method is called to the when finalize() method is called. The container is at the core of the Spring Framework. Spring’s container uses dependency injection (DI) to manage the components that make up an application

4 Categories of container implementations
BeanFactory defined by the org.springframework.beans.factory.BeanFactory package. The simplest of containers, providing basic support for DI. ApplicationContext defined by the org.springframework.context.ApplicationContext package. ability to read textual messages from a properties file. ability to publish application events to interested event listeners

5 BeanFactory A bean factory is an implementation of the Factory design pattern. It is a class whose responsibility is to create and dispense beans; general-purpose factory. Because a bean factory knows about many objects within an application, it is able to create associations between collaborating objects as they are instantiated. When a bean factory hands out objects, those objects are fully configured, are aware of their collaborating objects, and are ready to use.

6 XmlBeanFactory A most commonly used is org.springframework.beans.factory.xml.XmlBeanFactory which loads its beans based on the definitions contained in an XML file. To create an XmlBeanFactory, you must pass an instance of org.springframework. core.io.Resource to the constructor. The Resource object will provide the XML to the factory. Most commonly used resource implementation is FileSystemResource. BeanFactory factory = new XmlBeanFactory(new FileSystemResource("c:/spring.xml"));

7 Lazily Loaded Beans The Beans are “lazily” loaded into bean factories i.e. while the bean factory will immediately load the bean definitions (the description of beans and their properties), the beans themselves will not be instantiated until they are needed.

8 Retrieving Bean To retrieve a bean from a BeanFactory, simply call the getBean() method, passing the ID of the bean you want to retrieve: MyBean myBean = (MyBean) factory.getBean("myBean"); When getBean() is called, the factory will instantiate the bean and set the bean’s properties using DI. With this, the life of a bean starts in the Spring container.

9 ApplicationContext An ApplicationContext is much the same as a BeanFactory. Both load bean definitions, wire beans together, and dispense beans upon request. But an ApplicationContext offers much more: Application contexts provide a means for resolving text messages, including support for internationalization. Application contexts can publish events to beans that are registered as listeners.

10 ApplicationContext Implementations of ApplicationContext are three that are commonly used: ClassPathXmlApplicationContext Loads a context definition from an XML file located in the classpath. FileSystemXmlApplicationContext Loads a context definition from an XML file in the file system.

11 ApplicationContext ApplicationContext context =
To load an application context from within the application’s classpath using ClassPathXmlApplicationContext: ApplicationContext context = new ClassPathXmlApplicationContext(“spring.xml"); To load a FileSystemXmlApplicationContext: new FileSystemXmlApplicationContext("c:/spring.xml");

12 ApplicationContext The difference between these uses of FileSystemXmlApplicationContext and ClassPathXmlApplicationContext is that FileSystemXmlApplicationContext will look for spring.xml in a specific location within the file system, whereas ClassPathXmlApplicationContext will look for spring.xml anywhere in the classpath.

13 BeanFactory & ApplicationContext
In either case, you can retrieve a bean from an ApplicationContext just as you would from a BeanFactory: by using the getBean() method.

14 Bean Scope Prototype : Singleton :
A new object is created each time it is injected. Singleton : The same object is returned each time it is injected.

15 Setter Injection <bean id=“cir" class="org.java.Circle">
<property name=“a" value=“10"/> <property name=“msg" value=“Hello"/> </bean>

16 Constructor Injection
<bean id=“cir" class="org.java.Circle"> <constructor-arg value="10" index="1"/> <constructor-arg value="Hello"/> </bean>

17 Constructor Injection
<bean id="tri" class="org.java.Triangle"> <constructor-arg type="int" value="10"/> </bean>

18 Autowiring So far you’ve seen how to wire all of your bean’s properties using either the <constructor-arg> or the <property> element. In a large application, however, all of this explicit wiring can result in a lot of XML. Rather than explicitly wiring all of your bean’s properties, you can have Spring automatically figure out how to wire beans together by setting the autowire property on each <bean> that you want Spring to autowire. The autowiring in specified at the autowire attribute inside <bean/>. The four types of autowiring:

19 Autowiring ■ byname:: Attempts to find a bean in the container whose ID is the same as the name of the property being wired. If a matching bean is not found, the property will remain unwired. ■ byType:: Attempts to find a single bean in the container whose type matches the type of the property being wired. If no matching bean is found, the property will not be wired. If more than one bean matches, an org.springframework.beans.factory.UnsatisfiedDependencyException will be thrown.

20 Autowiring ■ constructor:: Tries to match up one or more beans in the container with the parameters of one of the constructors of the bean being wired. In the event of ambiguous beans or ambiguous constructors, an org.springframework. beans.factory.UnsatisfiedDependencyException will be thrown. ■ autodetect:: Attempts to autowire by constructor first and then using byType. Ambiguity is handled the same way as with constructor and byType wiring.

21 Summary Factory Method Adding JARs Spring Containers getBean()
BeanFactory ApplicationContext getBean() <property> <constrtuctor-arg> Type Index Injecting Object Reference Point Class Inner Beans Autowire byname byType constructor

22 Wiring Collection Value and ref are only useful when your bean’s properties are singular. Spring offers four types of collection configuration elements when configuring collection of values.

23 Injecting Collection <list>
This helps in wiring ie injecting a list of values, allowing duplicates. <set> This helps in wiring a set of values but without any duplicates. <map> This can be used to inject a collection of name-value pairs where name and value can be of any type. <props> This can be used to inject a collection of name-value pairs where the name and value are both Strings.

24 <list> and <set>
<list> and <set> elements are useful when configuring properties that are either array or some implementation of java.util.Collection.

25 <map> and <props>
<map> and <props> these two elements are correspond to collection that are java.util.Map and java.util.Properties. The java.util.Map interface represents a mapping between a key and a value. The Map interface is not a subtype of the Collection interface. Therefore it behaves a bit different from the rest of the collection types.

26 <map> and <props>
The java.util.Properties class which represents a persistent set of properties. The Properties can be saved to a stream or loaded from a stream. Each key and its corresponding value in the property list is a string.

27 Java.util.List public interface List<E> extends Collection<E> E - the type of elements in this list. Syntax : private List<E> var_name;

28 Java.util.List private List<Integer> points;
<property name="points"> <list> <value>1</value> <value>2</value> </list> </property>

29 Java.util.List private List<Point> points;
<property name="points"> <list> <ref bean="one"/> <ref bean="two"/> </list> </property>

30 Java.util.Set public interface Set<E> extends Collection<E> E - the type of elements maintained by this set. Syntax : private Set<E> var_name;

31 Java.util.Set private Set<Integer> points;
<property name="points"> <set> <value>1</value> <value>2</value> </set> </property>

32 Java.util.Set private Set<Point> points;
<property name="points"> <set> <ref bean="one"/> <ref bean="two"/> </set> </property> NOTE :- *[one,two,three] are some external bean definition.

33 Java.util.Map Map<K,V>
K - the type of keys maintained by this map. V - the type of mapped values Syntax : Private Map<K,V> var_name;

34 Java.util.Map private Map<Integer, Integer> points;
<property name="points"> <map> <entry key="1" value="10" /> <entry key="2" value="20" /> <entry key="3" value="30" /> </map> </property>

35 Java.util.Map System.out.println("Key :"+a1);
for (Integer a1 : points.keySet()) { System.out.println("Key :"+a1); System.out.println("Value :"+getPoints().get(a1)); }

36 Java.util.Map private Map<Integer, Point> points;
<property name="points"> <map> <entry key="1" value-ref=“one" /> <entry key="2" value-ref=“two" /> <entry key="3" value-ref=“three" /> </map> </property> NOTE :- *[one,two,three] are some external bean definition.

37 Java.util.Map for(int key : points.keySet()){ } s.o.p(“Key :”+key);
s.o.p(“Value : (“+getPoints().get(key).getX()+”,”+getPoints().get(key).getY()+”)”); }

38 Java.util.Properties public class Properties extends Hashtable<Object,Object> Syntax : private Properties var_name;

39 Java.util.Properties private Properties pros;
<property name="pros"> <props> <prop <prop </props> </property>

40 Java.util.Properties for(Object key : points.keySet()){ }
s.o.p(“Key :”+key); s.o.p(“Value : (“+getPoints().getProperty(key),null)); }

41 Read from Properties file
org.springframework.context.support.ResourceBundleMessageSource basename basenames <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource"> <property name="basenames“ > <list> <value>myMsg</value> <value>myProperty</value> </list> </property> </bean>

42 Database connectivity
Connection con; (import java.sql.Connection) Statement st; (import java.sql.Statement) dataSource : org.springframework.jdbc.datasource.DriverManagerDataSource driverClassName url username (Optional) password (Optional)

43 Database connectivity
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName” value="org.apache.derby.jdbc.ClientDriver"/> <property name="url" value="jdbc:derby://localhost:1527/myDB"/> <property name="username" value="app"/> <property name="password" value="app"/> </bean>

44 Database connectivity
Data Definition Language (DDL) : (create ,alter ,drop etc.) con = getDs().getConnection(); st = con.createStatement(); st.execute(sql); Data Manipulation Language (DML) : (insert ,update , delete etc.) st.executeUpdate(sql);

45 Database connectivity
Data Manipulation Language (DML) : (select) con = getDs().getConnection(); st = con.createStatement(); st.executeQuery(sql);

46 PreparedStatement PreparedStatement pst;
pst = con.prepareStatement(sql); pst.setInt(1, getC().getC_id()); ResultSet rs = pst.executeQuery();

47 Using JDBC API Main getBean(“”circleDAO”); Circle int c_id;
String c_name; circleDAOimpl Circle c; DataSource ds; <bean id=“Circle”/> <bean id=“DataSource”/>

48 Using JdbcTemplate Main getBean(“”circleDAO”); Circle int c_id;
String c_name; circleDAOimpl Circle c; JdbcTemplate jdbcT; <bean id=“Circle”/> <bean id=“jdbcTemplate”/> <bean id=“DataSource”/>

49 JdbcTemplate Spring JdbcTemplate is a powerful mechanism to connect to the database and execute SQL queries. It internally uses JDBC API, but eliminates a lot of problems of JDBC API. org.springframework.jdbc.core.JdbcTemplate dataSource

50 JdbcTemplate Problems of JDBC API :
We need to write a lot of code before and after executing the query, such as creating connection, statement, closing resultset, connection etc. We need to perform exception handling code on the database logic. Repetition of all these codes from one to another database logic is a time consuming task.

51 JdbcTemplate Advantage of Spring JdbcTemplate :
Spring JdbcTemplate eliminates all the above mentioned problems of JDBC API. It provides you methods to write the queries directly.

52 JdbcTemplate <bean id="jt" class="org.springframework.jdbc.core.JdbcTemplate"> <property name=" dataSource " ref="dataSource"/> </bean> NOTE :- *[dataSource] is the external bean definition.

53 JdbcTemplate Returning Integer value : Returning Long value :
queryForInt("SELECT COUNT(*) FROM circle"); Returning Long value : queryForLong(“SELECT salary FROM employee");

54 JdbcTemplate Returning String value : Returning Class :
String sql = "SELECT c_name FROM circle WHERE c_id = ? "; queryForObject(sql, new Object[] {circle_id}, String.class); Returning Class : String sql = "SELECT * FROM circle WHERE c_id = ?"; queryForObject(sql, new Object[] {circle_id}, new RowMapper<Circle>);

55 JdbcTemplate Returning List<Circle> :
String sql = "SELECT * FROM circle"; queryForObject(sql, new RowMapper<Circle>);

56 JdbcTemplate Insert Data :
String sql = "INSERT INTO circle VALUES(?,?)"; update(sql, new Object[]{getC().getC_id(),getC().getC_name()});

57 Hibernate

58 Hibernate An ORM tool. Implements JPA.

59 Hibernate Hibernate is an Object-Relational Mapping(ORM) solution for JAVA and it raised as an open source persistent framework created by Gavin King in It is a powerful, high performance Object-Relational Persistence and Query service for any Java Application. Hibernate maps Java classes to database tables and from Java data types to SQL data types and relieve the developer from 95% of common data persistence related programming tasks.

60 Hibernate position

61 The Problem Class User Class ID Name Address Phone Date of Birth

62 The Problem Table Class ID Name Addr Phone DOB User Class ID Name
Address Phone Date of Birth

63 The Problem Table Class ID Name Addr Phone DOB User Class ID Name
Address Phone Date of Birth Relational Object Mapping

64 The Problem Mapping member variables to columns. Handling data types.
Managing changes to object state.

65 Without Hibernate Database Configuration. The Model Object.
Service method to create the model Object. Database Design. DAO method to save the object using SQL queries.

66 Using Hibernate Database Configuration – Hibernate configuration
The Model Object – Annotations Service method to create the model object – Use The Hibernate API Database Design – Not needed..! DAO method to save the object using SQL queries – Not needed..!

67 Hibernate Advantages Hibernate takes care of mapping Java classes to database tables using XML files and without writing any line of code. Provides simple APIs for storing and retrieving Java objects directly to and from the database. If there is change in Database or in any table then the only need to change XML file properties. Abstract away the unfamiliar SQL types and provide us to work around familiar Java Objects. Hibernate does not require an application server to operate. Manipulates Complex associations of objects of your database. Minimize database access with smart fetching strategies. Provides Simple querying of data.

68 Hibernate Architecture
Class Objects APIs

69 Hibernate Architecture
Configuration : The Configuration object is the first Hibernate object you create in any Hibernate application and usually created only once during application initialization.  The Configuration object provides two keys components: 1.) Database Connection : This is handled through configuration files supported by Hibernate - hibernate.cfg.xml. 2.) Class Mapping Setup : This component creates the connection between the Java classes and database tables.

70 Hibernate Architecture
SessionFactory : Configuration object is used to create a SessionFactory object which intern configures Hibernate for the application. The SessionFactory is heavyweight object so usually it is created during application start up and kept for later use.  You would need one SessionFactory object per database using a separate configuration file. So if you are using multiple databases then you would have to create multiple SessionFactory objects. The org.hibernate.SessionFactory interface provides factory method to get the object of Session.

71 Hibernate Architecture
Session : A Session is used to get a physical connection with a database. The Session object is lightweight and designed to be instantiated each time an interaction is needed with the database.  The session object provides an interface between the application and data stored in the database. The org.hibernate.Session interface provides methods to insert, update and delete the object.

72 Hibernate Architecture
Transaction : A Transaction represents a unit of work with the database and most of the RDBMS supports transaction functionality. Transactions in Hibernate are handled by an underlying transaction manager and transaction (from JDBC or JTA). The org.hibernate.Transaction interface provides methods for transaction management.

73 Hibernate Architecture
Query : Query objects use SQL or Hibernate Query Language (HQL) string to retrieve data from the database and create objects. A Query instance is used to bind query parameters, limit the number of results returned by the query, and finally to execute the query.

74 Hibernate Architecture
Criteria : Criteria object are used to create and execute object oriented criteria queries to retrieve objects.

75 Singular Database Configuration SessionFactory Session- 1
Transaction - 1 Session - 2 Transaction – 1 Transaction – 2

76 Multiple Database Configuration – 1 SessionFactory Session – 1
Transaction - 1 Session – 2 Configuration – 2 SessionFactory Session – 1 Transaction - 1 Session – 2


Download ppt "Unit-2 Beans and Containers."

Similar presentations


Ads by Google