Spring – Injecting Inner Beans

Spring – Injecting Inner Beans ”; Previous Next As you know Java inner classes are defined within the scope of other classes, similarly, inner beans are beans that are defined within the scope of another bean. Thus, a <bean/> element inside the <property/> or <constructor-arg/> elements is called inner bean and it is shown below. <?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-3.0.xsd”> <bean id = “outerBean” class = “…”> <property name = “target”> <bean id = “innerBean” class = “…”/> </property> </bean> </beans> Example Let us have working Eclipse IDE in place and follow the following steps to create a Spring application − Steps Description 1 Create a project with a name SpringExample and create a package com.tutorialspoint under the src folder in the created project. 2 Add required Spring libraries using Add External JARs option as explained in the Spring Hello World Example chapter. 3 Create Java classes TextEditor, SpellChecker and MainApp under the com.tutorialspoint package. 4 Create Beans configuration file Beans.xml under the src folder. 5 The final step is to create the content of all the Java files and Bean Configuration file and run the application as explained below. Here is the content of TextEditor.java file − package com.tutorialspoint; public class TextEditor { private SpellChecker spellChecker; // a setter method to inject the dependency. public void setSpellChecker(SpellChecker spellChecker) { System.out.println(“Inside setSpellChecker.” ); this.spellChecker = spellChecker; } // a getter method to return spellChecker public SpellChecker getSpellChecker() { return spellChecker; } public void spellCheck() { spellChecker.checkSpelling(); } } Following is the content of another dependent class file SpellChecker.java − package com.tutorialspoint; public class SpellChecker { public SpellChecker(){ System.out.println(“Inside SpellChecker constructor.” ); } public void checkSpelling(){ System.out.println(“Inside checkSpelling.” ); } } Following is the content of the MainApp.java file − package com.tutorialspoint; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class MainApp { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext(“Beans.xml”); TextEditor te = (TextEditor) context.getBean(“textEditor”); te.spellCheck(); } } Following is the configuration file Beans.xml which has configuration for the setter-based injection but using inner beans − <?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-3.0.xsd”> <!– Definition for textEditor bean using inner bean –> <bean id = “textEditor” class = “com.tutorialspoint.TextEditor”> <property name = “spellChecker”> <bean id = “spellChecker” class = “com.tutorialspoint.SpellChecker”/> </property> </bean> </beans> Once you are done creating the source and bean configuration files, let us run the application. If everything is fine with your application, it will print the following message − Inside SpellChecker constructor. Inside setSpellChecker. Inside checkSpelling. Print Page Previous Next Advertisements ”;

Spring – Bean Definition

Spring – Bean Definition ”; Previous Next The objects that form the backbone of your application and that are managed by the Spring IoC container are called beans. A bean is an object that is instantiated, assembled, and otherwise managed by a Spring IoC container. These beans are created with the configuration metadata that you supply to the container. For example, in the form of XML <bean/> definitions which you have already seen in the previous chapters. Bean definition contains the information called configuration metadata, which is needed for the container to know the following − How to create a bean Bean”s lifecycle details Bean”s dependencies All the above configuration metadata translates into a set of the following properties that make up each bean definition. Sr.No. Properties & Description 1 class This attribute is mandatory and specifies the bean class to be used to create the bean. 2 name This attribute specifies the bean identifier uniquely. In XMLbased configuration metadata, you use the id and/or name attributes to specify the bean identifier(s). 3 scope This attribute specifies the scope of the objects created from a particular bean definition and it will be discussed in bean scopes chapter. 4 constructor-arg This is used to inject the dependencies and will be discussed in subsequent chapters. 5 properties This is used to inject the dependencies and will be discussed in subsequent chapters. 6 autowiring mode This is used to inject the dependencies and will be discussed in subsequent chapters. 7 lazy-initialization mode A lazy-initialized bean tells the IoC container to create a bean instance when it is first requested, rather than at the startup. 8 initialization method A callback to be called just after all necessary properties on the bean have been set by the container. It will be discussed in bean life cycle chapter. 9 destruction method A callback to be used when the container containing the bean is destroyed. It will be discussed in bean life cycle chapter. Spring Configuration Metadata Spring IoC container is totally decoupled from the format in which this configuration metadata is actually written. Following are the three important methods to provide configuration metadata to the Spring Container − XML based configuration file. Annotation-based configuration Java-based configuration You already have seen how XML-based configuration metadata is provided to the container, but let us see another sample of XML-based configuration file with different bean definitions including lazy initialization, initialization method, and destruction method − <?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-3.0.xsd”> <!– A simple bean definition –> <bean id = “…” class = “…”> <!– collaborators and configuration for this bean go here –> </bean> <!– A bean definition with lazy init set on –> <bean id = “…” class = “…” lazy-init = “true”> <!– collaborators and configuration for this bean go here –> </bean> <!– A bean definition with initialization method –> <bean id = “…” class = “…” init-method = “…”> <!– collaborators and configuration for this bean go here –> </bean> <!– A bean definition with destruction method –> <bean id = “…” class = “…” destroy-method = “…”> <!– collaborators and configuration for this bean go here –> </bean> <!– more bean definitions go here –> </beans> You can check Spring Hello World Example to understand how to define, configure and create Spring Beans. We will discuss about Annotation Based Configuration in a separate chapter. It is intentionally discussed in a separate chapter as we want you to grasp a few other important Spring concepts, before you start programming with Spring Dependency Injection with Annotations. Print Page Previous Next Advertisements ”;

Spring – Bean Definition Inheritance

Spring – Bean Definition Inheritance ”; Previous Next A bean definition can contain a lot of configuration information, including constructor arguments, property values, and container-specific information such as initialization method, static factory method name, and so on. A child bean definition inherits configuration data from a parent definition. The child definition can override some values, or add others, as needed. Spring Bean definition inheritance has nothing to do with Java class inheritance but the inheritance concept is same. You can define a parent bean definition as a template and other child beans can inherit the required configuration from the parent bean. When you use XML-based configuration metadata, you indicate a child bean definition by using the parent attribute, specifying the parent bean as the value of this attribute. Example Let us have a working Eclipse IDE in place and take the following steps to create a Spring application − Steps Description 1 Create a project with a name SpringExample and create a package com.tutorialspoint under the src folder in the created project. 2 Add required Spring libraries using Add External JARs option as explained in the Spring Hello World Example chapter. 3 Create Java classes HelloWorld, HelloIndia and MainApp under the com.tutorialspoint package. 4 Create Beans configuration file Beans.xml under the src folder. 5 The final step is to create the content of all the Java files and Bean Configuration file and run the application as explained below. Following is the configuration file Beans.xml where we defined “helloWorld” bean which has two properties message1 and message2. Next “helloIndia” bean has been defined as a child of “helloWorld” bean by using parent attribute. The child bean inherits message2 property as is, and overrides message1 property and introduces one more property message3. <?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-3.0.xsd”> <bean id = “helloWorld” class = “com.tutorialspoint.HelloWorld”> <property name = “message1” value = “Hello World!”/> <property name = “message2” value = “Hello Second World!”/> </bean> <bean id =”helloIndia” class = “com.tutorialspoint.HelloIndia” parent = “helloWorld”> <property name = “message1” value = “Hello India!”/> <property name = “message3” value = “Namaste India!”/> </bean> </beans> Here is the content of HelloWorld.java file − package com.tutorialspoint; public class HelloWorld { private String message1; private String message2; public void setMessage1(String message){ this.message1 = message; } public void setMessage2(String message){ this.message2 = message; } public void getMessage1(){ System.out.println(“World Message1 : ” + message1); } public void getMessage2(){ System.out.println(“World Message2 : ” + message2); } } Here is the content of HelloIndia.java file − package com.tutorialspoint; public class HelloIndia { private String message1; private String message2; private String message3; public void setMessage1(String message){ this.message1 = message; } public void setMessage2(String message){ this.message2 = message; } public void setMessage3(String message){ this.message3 = message; } public void getMessage1(){ System.out.println(“India Message1 : ” + message1); } public void getMessage2(){ System.out.println(“India Message2 : ” + message2); } public void getMessage3(){ System.out.println(“India Message3 : ” + message3); } } Following is the content of the MainApp.java file − package com.tutorialspoint; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class MainApp { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext(“Beans.xml”); HelloWorld objA = (HelloWorld) context.getBean(“helloWorld”); objA.getMessage1(); objA.getMessage2(); HelloIndia objB = (HelloIndia) context.getBean(“helloIndia”); objB.getMessage1(); objB.getMessage2(); objB.getMessage3(); } } Once you are done creating the source and bean configuration files, let us run the application. If everything is fine with your application, it will print the following message − World Message1 : Hello World! World Message2 : Hello Second World! India Message1 : Hello India! India Message2 : Hello Second World! India Message3 : Namaste India! If you observed here, we did not pass message2 while creating “helloIndia” bean, but it got passed because of Bean Definition Inheritance. Bean Definition Template You can create a Bean definition template, which can be used by other child bean definitions without putting much effort. While defining a Bean Definition Template, you should not specify the class attribute and should specify abstract attribute and should specify the abstract attribute with a value of true as shown in the following code snippet − <?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-3.0.xsd”> <bean id = “beanTeamplate” abstract = “true”> <property name = “message1” value = “Hello World!”/> <property name = “message2” value = “Hello Second World!”/> <property name = “message3” value = “Namaste India!”/> </bean> <bean id = “helloIndia” class = “com.tutorialspoint.HelloIndia” parent = “beanTeamplate”> <property name = “message1” value = “Hello India!”/> <property name = “message3” value = “Namaste India!”/> </bean> </beans> The parent bean cannot be instantiated on its own because it is incomplete, and it is also explicitly marked as abstract. When a definition is abstract like this, it is usable only as a pure template bean definition that serves as a parent definition for child definitions. Print Page Previous Next Advertisements ”;

Spring – Transaction Management

Spring – Transaction Management ”; Previous Next A database transaction is a sequence of actions that are treated as a single unit of work. These actions should either complete entirely or take no effect at all. Transaction management is an important part of RDBMS-oriented enterprise application to ensure data integrity and consistency. The concept of transactions can be described with the following four key properties described as ACID − Atomicity − A transaction should be treated as a single unit of operation, which means either the entire sequence of operations is successful or unsuccessful. Consistency − This represents the consistency of the referential integrity of the database, unique primary keys in tables, etc. Isolation − There may be many transaction processing with the same data set at the same time. Each transaction should be isolated from others to prevent data corruption. Durability − Once a transaction has completed, the results of this transaction have to be made permanent and cannot be erased from the database due to system failure. A real RDBMS database system will guarantee all four properties for each transaction. The simplistic view of a transaction issued to the database using SQL is as follows − Begin the transaction using begin transaction command. Perform various deleted, update or insert operations using SQL queries. If all the operation are successful then perform commit otherwise rollback all the operations. Spring framework provides an abstract layer on top of different underlying transaction management APIs. Spring”s transaction support aims to provide an alternative to EJB transactions by adding transaction capabilities to POJOs. Spring supports both programmatic and declarative transaction management. EJBs require an application server, but Spring transaction management can be implemented without the need of an application server. Local vs. Global Transactions Local transactions are specific to a single transactional resource like a JDBC connection, whereas global transactions can span multiple transactional resources like transaction in a distributed system. Local transaction management can be useful in a centralized computing environment where application components and resources are located at a single site, and transaction management only involves a local data manager running on a single machine. Local transactions are easier to be implemented. Global transaction management is required in a distributed computing environment where all the resources are distributed across multiple systems. In such a case, transaction management needs to be done both at local and global levels. A distributed or a global transaction is executed across multiple systems, and its execution requires coordination between the global transaction management system and all the local data managers of all the involved systems. Programmatic vs. Declarative Spring supports two types of transaction management − Programmatic transaction management − This means that you have to manage the transaction with the help of programming. That gives you extreme flexibility, but it is difficult to maintain. Declarative transaction management − This means you separate transaction management from the business code. You only use annotations or XML-based configuration to manage the transactions. Declarative transaction management is preferable over programmatic transaction management though it is less flexible than programmatic transaction management, which allows you to control transactions through your code. But as a kind of crosscutting concern, declarative transaction management can be modularized with the AOP approach. Spring supports declarative transaction management through the Spring AOP framework. Spring Transaction Abstractions The key to the Spring transaction abstraction is defined by the org.springframework.transaction.PlatformTransactionManager interface, which is as follows − public interface PlatformTransactionManager { TransactionStatus getTransaction(TransactionDefinition definition); throws TransactionException; void commit(TransactionStatus status) throws TransactionException; void rollback(TransactionStatus status) throws TransactionException; } Sr.No Method & Description 1 TransactionStatus getTransaction(TransactionDefinition definition) This method returns a currently active transaction or creates a new one, according to the specified propagation behavior. 2 void commit(TransactionStatus status) This method commits the given transaction, with regard to its status. 3 void rollback(TransactionStatus status) This method performs a rollback of the given transaction. The TransactionDefinition is the core interface of the transaction support in Spring and it is defined as follows − public interface TransactionDefinition { int getPropagationBehavior(); int getIsolationLevel(); String getName(); int getTimeout(); boolean isReadOnly(); } Sr.No Method & Description 1 int getPropagationBehavior() This method returns the propagation behavior. Spring offers all of the transaction propagation options familiar from EJB CMT. 2 int getIsolationLevel() This method returns the degree to which this transaction is isolated from the work of other transactions. 3 String getName() This method returns the name of this transaction. 4 int getTimeout() This method returns the time in seconds in which the transaction must complete. 5 boolean isReadOnly() This method returns whether the transaction is read-only. Following are the possible values for isolation level − Sr.No Isolation & Description 1 TransactionDefinition.ISOLATION_DEFAULT This is the default isolation level. 2 TransactionDefinition.ISOLATION_READ_COMMITTED Indicates that dirty reads are prevented; non-repeatable reads and phantom reads can occur. 3 TransactionDefinition.ISOLATION_READ_UNCOMMITTED Indicates that dirty reads, non-repeatable reads, and phantom reads can occur. 4 TransactionDefinition.ISOLATION_REPEATABLE_READ Indicates that dirty reads and non-repeatable reads are prevented; phantom reads can occur. 5 TransactionDefinition.ISOLATION_SERIALIZABLE Indicates that dirty reads, non-repeatable reads, and phantom reads are prevented. Following are the possible values for propagation types − Sr.No. Propagation & Description 1 TransactionDefinition.PROPAGATION_MANDATORY Supports a current transaction; throws an exception if no current transaction exists. 2 TransactionDefinition.PROPAGATION_NESTED Executes within a nested transaction if a current transaction exists. 3 TransactionDefinition.PROPAGATION_NEVER Does not support a current transaction; throws an exception if a current transaction exists. 4 TransactionDefinition.PROPAGATION_NOT_SUPPORTED Does not support a current transaction; rather always execute nontransactionally. 5 TransactionDefinition.PROPAGATION_REQUIRED Supports a current transaction; creates a new one if none exists. 6 TransactionDefinition.PROPAGATION_REQUIRES_NEW Creates a new transaction, suspending the current transaction if one exists. 7 TransactionDefinition.PROPAGATION_SUPPORTS Supports a current transaction; executes non-transactionally if none exists. 8 TransactionDefinition.TIMEOUT_DEFAULT Uses the default timeout of the underlying transaction system, or none if timeouts are not supported. The TransactionStatus interface provides a simple way for transactional code to control transaction execution and query transaction status. public interface TransactionStatus extends SavepointManager { boolean isNewTransaction(); boolean hasSavepoint(); void setRollbackOnly(); boolean isRollbackOnly(); boolean isCompleted(); } Sr.No. Method

Spring – Bean Post Processors

Spring – Bean Post Processors ”; Previous Next The BeanPostProcessor interface defines callback methods that you can implement to provide your own instantiation logic, dependency-resolution logic, etc. You can also implement some custom logic after the Spring container finishes instantiating, configuring, and initializing a bean by plugging in one or more BeanPostProcessor implementations. You can configure multiple BeanPostProcessor interfaces and you can control the order in which these BeanPostProcessor interfaces execute by setting the order property provided the BeanPostProcessor implements the Ordered interface. The BeanPostProcessors operate on bean (or object) instances, which means that the Spring IoC container instantiates a bean instance and then BeanPostProcessor interfaces do their work. An ApplicationContext automatically detects any beans that are defined with the implementation of the BeanPostProcessor interface and registers these beans as postprocessors, to be then called appropriately by the container upon bean creation. Example The following examples show how to write, register, and use BeanPostProcessors in the context of an ApplicationContext. Let us have a working Eclipse IDE in place and take the following steps to create a Spring application − Steps Description 1 Create a project with a name SpringExample and create a package com.tutorialspoint under the src folder in the created project. 2 Add required Spring libraries using Add External JARs option as explained in the Spring Hello World Example chapter. 3 Create Java classes HelloWorld, InitHelloWorld and MainApp under the com.tutorialspoint package. 4 Create Beans configuration file Beans.xml under the src folder. 5 The final step is to create the content of all the Java files and Bean Configuration file and run the application as explained below. Here is the content of HelloWorld.java file − package com.tutorialspoint; public class HelloWorld { private String message; public void setMessage(String message){ this.message = message; } public void getMessage(){ System.out.println(“Your Message : ” + message); } public void init(){ System.out.println(“Bean is going through init.”); } public void destroy(){ System.out.println(“Bean will destroy now.”); } } This is a very basic example of implementing BeanPostProcessor, which prints a bean name before and after initialization of any bean. You can implement more complex logic before and after intializing a bean because you have access on bean object inside both the post processor methods. Here is the content of InitHelloWorld.java file − package com.tutorialspoint; import org.springframework.beans.factory.config.BeanPostProcessor; import org.springframework.beans.BeansException; public class InitHelloWorld implements BeanPostProcessor { public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { System.out.println(“BeforeInitialization : ” + beanName); return bean; // you can return any other object as well } public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { System.out.println(“AfterInitialization : ” + beanName); return bean; // you can return any other object as well } } Following is the content of the MainApp.java file. Here you need to register a shutdown hook registerShutdownHook() method that is declared on the AbstractApplicationContext class. This will ensures a graceful shutdown and calls the relevant destroy methods. package com.tutorialspoint; import org.springframework.context.support.AbstractApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class MainApp { public static void main(String[] args) { AbstractApplicationContext context = new ClassPathXmlApplicationContext(“Beans.xml”); HelloWorld obj = (HelloWorld) context.getBean(“helloWorld”); obj.getMessage(); context.registerShutdownHook(); } } Following is the configuration file Beans.xml required for init and destroy methods − <?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-3.0.xsd”> <bean id = “helloWorld” class = “com.tutorialspoint.HelloWorld” init-method = “init” destroy-method = “destroy”> <property name = “message” value = “Hello World!”/> </bean> <bean class = “com.tutorialspoint.InitHelloWorld” /> </beans> Once you are done with creating the source and bean configuration files, let us run the application. If everything is fine with your application, it will print the following message − BeforeInitialization : helloWorld Bean is going through init. AfterInitialization : helloWorld Your Message : Hello World! Bean will destroy now. Print Page Previous Next Advertisements ”;

Spring – Discussion

Discuss Spring ”; Previous Next 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 was initially written by Rod Johnson and was first released under the Apache 2.0 license in June 2003. This tutorial has been written based on Spring Framework version 4.1.6 released in Mar 2015. Print Page Previous Next Advertisements ”;

Spring – Logging with Log4J

Spring – Logging with Log4J ”; Previous Next This is a very easy-to-use Log4J functionality inside Spring applications. The following example will take you through simple steps to explain the simple integration between Log4J and Spring. We assume you already have log4J installed on your machine. If you do not have it then you can download it from https://logging.apache.org/ and simply extract the zipped file in any folder. We will use only log4j-x.y.z.jar in our project. Next, let us have a working Eclipse IDE in place and take the following steps to develop a Dynamic Form-based Web Application using Spring Web Framework − Steps Description 1 Create a project with a name SpringExample and create a package com.tutorialspoint under the src folder in the created project. 2 Add required Spring libraries using Add External JARs option as explained in the Spring Hello World Example chapter. 3 Add log4j library log4j-x.y.z.jar as well in your project using using Add External JARs. 4 Create Java classes HelloWorld and MainApp under the com.tutorialspoint package. 5 Create Beans configuration file Beans.xml under the src folder. 6 Create log4J configuration file log4j.properties under the src folder. 7 The final step is to create the content of all the Java files and Bean Configuration file and run the application as explained below. Here is the content of HelloWorld.java file package com.tutorialspoint; public class HelloWorld { private String message; public void setMessage(String message){ this.message = message; } public void getMessage() { System.out.println(“Your Message : ” + message); } } Following is the content of the second file MainApp.java package com.tutorialspoint; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.apache.log4j.Logger; public class MainApp { static Logger log = Logger.getLogger(MainApp.class.getName()); public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext(“Beans.xml”); log.info(“Going to create HelloWord Obj”); HelloWorld obj = (HelloWorld) context.getBean(“helloWorld”); obj.getMessage(); log.info(“Exiting the program”); } } You can generate debug and error message in a similar way as we have generated info messages. Now let us see the content of Beans.xml file <?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-3.0.xsd”> <bean id = “helloWorld” class = “com.tutorialspoint.HelloWorld”> <property name = “message” value = “Hello World!”/> </bean> </beans> Following is the content of log4j.properties which defines the standard rules required for Log4J to produce log messages # Define the root logger with appender file log4j.rootLogger = DEBUG, FILE # Define the file appender log4j.appender.FILE=org.apache.log4j.FileAppender # Set the name of the file log4j.appender.FILE.File=C:\log.out # Set the immediate flush to true (default) log4j.appender.FILE.ImmediateFlush=true # Set the threshold to debug mode log4j.appender.FILE.Threshold=debug # Set the append to false, overwrite log4j.appender.FILE.Append=false # Define the layout for file appender log4j.appender.FILE.layout=org.apache.log4j.PatternLayout log4j.appender.FILE.layout.conversionPattern=%m%n Once you are done with creating source and bean configuration files, let us run the application. If everything is fine with your application, this will print the following message in Eclipse console − Your Message : Hello World! If you check your C:\ drive, then you should find your log file log.out with various log messages, like something as follows − <!– initialization log messages –> Going to create HelloWord Obj Returning cached instance of singleton bean ”helloWorld” Exiting the program Jakarta Commons Logging (JCL) API Alternatively you can use Jakarta Commons Logging (JCL) API to generate a log in your Spring application. JCL can be downloaded from the https://jakarta.apache.org/commons/logging/. The only file we technically need out of this package is the commons-logging-x.y.z.jar file, which needs to be placed in your classpath in a similar way as you had put log4j-x.y.z.jar in the above example. To use the logging functionality you need a org.apache.commons.logging.Log object and then you can call one of the following methods as per your requirment − fatal(Object message) error(Object message) warn(Object message) info(Object message) debug(Object message) trace(Object message) Following is the replacement of MainApp.java, which makes use of JCL API package com.tutorialspoint; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.apache.commons.logging. Log; import org.apache.commons.logging. LogFactory; public class MainApp { static Log log = LogFactory.getLog(MainApp.class.getName()); public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext(“Beans.xml”); log.info(“Going to create HelloWord Obj”); HelloWorld obj = (HelloWorld) context.getBean(“helloWorld”); obj.getMessage(); log.info(“Exiting the program”); } } You have to make sure that you have included commons-logging-x.y.z.jar file in your project, before compiling and running the program. Now keeping the rest of the configuration and content unchanged in the above example, if you compile and run your application, you will get a similar result as what you got using Log4J API. Print Page Previous Next Advertisements ”;

Spring – Dependency Injection

Spring – Dependency Injection ”; Previous Next Every Java-based application has a few objects that work together to present what the end-user sees as a working application. When writing a complex Java application, application classes should be as independent as possible of other Java classes to increase the possibility to reuse these classes and to test them independently of other classes while unit testing. Dependency Injection (or sometime called wiring) helps in gluing these classes together and at the same time keeping them independent. Consider you have an application which has a text editor component and you want to provide a spell check. Your standard code would look something like this − public class TextEditor { private SpellChecker spellChecker; public TextEditor() { spellChecker = new SpellChecker(); } } What we”ve done here is, create a dependency between the TextEditor and the SpellChecker. In an inversion of control scenario, we would instead do something like this − public class TextEditor { private SpellChecker spellChecker; public TextEditor(SpellChecker spellChecker) { this.spellChecker = spellChecker; } } Here, the TextEditor should not worry about SpellChecker implementation. The SpellChecker will be implemented independently and will be provided to the TextEditor at the time of TextEditor instantiation. This entire procedure is controlled by the Spring Framework. Here, we have removed total control from the TextEditor and kept it somewhere else (i.e. XML configuration file) and the dependency (i.e. class SpellChecker) is being injected into the class TextEditor through a Class Constructor. Thus the flow of control has been “inverted” by Dependency Injection (DI) because you have effectively delegated dependances to some external system. The second method of injecting dependency is through Setter Methods of the TextEditor class where we will create a SpellChecker instance. This instance will be used to call setter methods to initialize TextEditor”s properties. Thus, DI exists in two major variants and the following two sub-chapters will cover both of them with examples − Sr.No. Dependency Injection Type & Description 1 Constructor-based dependency injection Constructor-based DI is accomplished when the container invokes a class constructor with a number of arguments, each representing a dependency on the other class. 2 Setter-based dependency injection Setter-based DI is accomplished by the container calling setter methods on your beans after invoking a no-argument constructor or no-argument static factory method to instantiate your bean. You can mix both, Constructor-based and Setter-based DI but it is a good rule of thumb to use constructor arguments for mandatory dependencies and setters for optional dependencies. The code is cleaner with the DI principle and decoupling is more effective when objects are provided with their dependencies. The object does not look up its dependencies and does not know the location or class of the dependencies, rather everything is taken care by the Spring Framework. Print Page Previous Next Advertisements ”;

Spring – Web MVC Framework

Spring – MVC Framework ”; Previous Next The Spring Web MVC framework provides Model-View-Controller (MVC) architecture and ready components that can be used to develop flexible and loosely coupled web applications. The MVC pattern results in separating the different aspects of the application (input logic, business logic, and UI logic), while providing a loose coupling between these elements. The Model encapsulates the application data and in general they will consist of POJO. The View is responsible for rendering the model data and in general it generates HTML output that the client”s browser can interpret. The Controller is responsible for processing user requests and building an appropriate model and passes it to the view for rendering. The DispatcherServlet The Spring Web model-view-controller (MVC) framework is designed around a DispatcherServlet that handles all the HTTP requests and responses. The request processing workflow of the Spring Web MVC DispatcherServlet is illustrated in the following diagram − Following is the sequence of events corresponding to an incoming HTTP request to DispatcherServlet − After receiving an HTTP request, DispatcherServlet consults the HandlerMapping to call the appropriate Controller. The Controller takes the request and calls the appropriate service methods based on used GET or POST method. The service method will set model data based on defined business logic and returns view name to the DispatcherServlet. The DispatcherServlet will take help from ViewResolver to pickup the defined view for the request. Once view is finalized, The DispatcherServlet passes the model data to the view which is finally rendered on the browser. All the above-mentioned components, i.e. HandlerMapping, Controller, and ViewResolver are parts of WebApplicationContext which is an extension of the plainApplicationContext with some extra features necessary for web applications. Required Configuration You need to map requests that you want the DispatcherServlet to handle, by using a URL mapping in the web.xml file. The following is an example to show declaration and mapping for HelloWeb DispatcherServlet example − <web-app id = “WebApp_ID” version = “2.4” xmlns = “http://java.sun.com/xml/ns/j2ee” xmlns:xsi = “http://www.w3.org/2001/XMLSchema-instance” xsi:schemaLocation = “http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd”> <display-name>Spring MVC Application</display-name> <servlet> <servlet-name>HelloWeb</servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>HelloWeb</servlet-name> <url-pattern>*.jsp</url-pattern> </servlet-mapping> </web-app> The web.xml file will be kept in the WebContent/WEB-INF directory of your web application. Upon initialization of HelloWeb DispatcherServlet, the framework will try to load the application context from a file named [servlet-name]-servlet.xml located in the application”s WebContent/WEB-INF directory. In this case, our file will be HelloWebservlet.xml. Next, <servlet-mapping> tag indicates what URLs will be handled by which DispatcherServlet. Here all the HTTP requests ending with .jsp will be handled by the HelloWeb DispatcherServlet. If you do not want to go with default filename as [servlet-name]-servlet.xml and default location as WebContent/WEB-INF, you can customize this file name and location by adding the servlet listener ContextLoaderListener in your web.xml file as follows − <web-app…> <!——– DispatcherServlet definition goes here—–> …. <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/HelloWeb-servlet.xml</param-value> </context-param> <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener> </web-app> Now, let us check the required configuration for HelloWeb-servlet.xml file, placed in your web application”s WebContent/WEB-INF directory − <beans xmlns = “http://www.springframework.org/schema/beans” xmlns:context = “http://www.springframework.org/schema/context” 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-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd”> <context:component-scan base-package = “com.tutorialspoint” /> <bean class = “org.springframework.web.servlet.view.InternalResourceViewResolver”> <property name = “prefix” value = “/WEB-INF/jsp/” /> <property name = “suffix” value = “.jsp” /> </bean> </beans> Following are the important points about HelloWeb-servlet.xml file − The [servlet-name]-servlet.xml file will be used to create the beans defined, overriding the definitions of any beans defined with the same name in the global scope. The <context:component-scan…> tag will be use to activate Spring MVC annotation scanning capability which allows to make use of annotations like @Controller and @RequestMapping etc. The InternalResourceViewResolver will have rules defined to resolve the view names. As per the above defined rule, a logical view named hello is delegated to a view implementation located at /WEB-INF/jsp/hello.jsp . The following section will show you how to create your actual components, i.e., Controller, Model, and View. Defining a Controller The DispatcherServlet delegates the request to the controllers to execute the functionality specific to it. The @Controller annotation indicates that a particular class serves the role of a controller. The @RequestMapping annotation is used to map a URL to either an entire class or a particular handler method. @Controller @RequestMapping(“/hello”) public class HelloController { @RequestMapping(method = RequestMethod.GET) public String printHello(ModelMap model) { model.addAttribute(“message”, “Hello Spring MVC Framework!”); return “hello”; } } The @Controller annotation defines the class as a Spring MVC controller. Here, the first usage of @RequestMapping indicates that all handling methods on this controller are relative to the /hello path. Next annotation @RequestMapping(method = RequestMethod.GET) is used to declare the printHello() method as the controller”s default service method to handle HTTP GET request. You can define another method to handle any POST request at the same URL. You can write the above controller in another form where you can add additional attributes in @RequestMapping as follows − @Controller public class HelloController { @RequestMapping(value = “/hello”, method = RequestMethod.GET) public String printHello(ModelMap model) { model.addAttribute(“message”, “Hello Spring MVC Framework!”); return “hello”; } } The value attribute indicates the URL to which the handler method is mapped and the method attribute defines the service method to handle HTTP GET request. The following important points are to be noted about the controller defined above − You will define required business logic inside a service method. You can call another method inside this method as per requirement. Based on the business logic defined, you will create a model within this method. You can use setter different model attributes and these attributes will be accessed by the view to present the final result. This example creates a model with its attribute “message”. A defined service method can return a String, which contains the name of the view to be used to render the model. This example returns “hello” as logical view name. Creating JSP Views Spring MVC supports many types of views for different presentation technologies. These include – JSPs, HTML, PDF, Excel worksheets, XML,

Spring – Java Based Configuration

Spring – Java Based Configuration ”; Previous Next So far you have seen how we configure Spring beans using XML configuration file. If you are comfortable with XML configuration, then it is really not required to learn how to proceed with Java-based configuration as you are going to achieve the same result using either of the configurations available. Java-based configuration option enables you to write most of your Spring configuration without XML but with the help of few Java-based annotations explained in this chapter. @Configuration & @Bean Annotations Annotating a class with the @Configuration indicates that the class can be used by the Spring IoC container as a source of bean definitions. The @Bean annotation tells Spring that a method annotated with @Bean will return an object that should be registered as a bean in the Spring application context. The simplest possible @Configuration class would be as follows − package com.tutorialspoint; import org.springframework.context.annotation.*; @Configuration public class HelloWorldConfig { @Bean public HelloWorld helloWorld(){ return new HelloWorld(); } } The above code will be equivalent to the following XML configuration − <beans> <bean id = “helloWorld” class = “com.tutorialspoint.HelloWorld” /> </beans> Here, the method name is annotated with @Bean works as bean ID and it creates and returns the actual bean. Your configuration class can have a declaration for more than one @Bean. Once your configuration classes are defined, you can load and provide them to Spring container using AnnotationConfigApplicationContext as follows − public static void main(String[] args) { ApplicationContext ctx = new AnnotationConfigApplicationContext(HelloWorldConfig.class); HelloWorld helloWorld = ctx.getBean(HelloWorld.class); helloWorld.setMessage(“Hello World!”); helloWorld.getMessage(); } You can load various configuration classes as follows − public static void main(String[] args) { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); ctx.register(AppConfig.class, OtherConfig.class); ctx.register(AdditionalConfig.class); ctx.refresh(); MyService myService = ctx.getBean(MyService.class); myService.doStuff(); } Example Let us have a working Eclipse IDE in place and take the following steps to create a Spring application − Steps Description 1 Create a project with a name SpringExample and create a package com.tutorialspoint under the src folder in the created project. 2 Add required Spring libraries using Add External JARs option as explained in the Spring Hello World Example chapter. 3 Because you are using Java-based annotations, so you also need to add CGLIB.jar from your Java installation directory and ASM.jar library which can be downloaded from asm.ow2.org. 4 Create Java classes HelloWorldConfig, HelloWorld and MainApp under the com.tutorialspoint package. 5 The final step is to create the content of all the Java files and Bean Configuration file and run the application as explained below. Here is the content of HelloWorldConfig.java file package com.tutorialspoint; import org.springframework.context.annotation.*; @Configuration public class HelloWorldConfig { @Bean public HelloWorld helloWorld(){ return new HelloWorld(); } } Here is the content of HelloWorld.java file package com.tutorialspoint; public class HelloWorld { private String message; public void setMessage(String message){ this.message = message; } public void getMessage(){ System.out.println(“Your Message : ” + message); } } Following is the content of the MainApp.java file package com.tutorialspoint; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.*; public class MainApp { public static void main(String[] args) { ApplicationContext ctx = new AnnotationConfigApplicationContext(HelloWorldConfig.class); HelloWorld helloWorld = ctx.getBean(HelloWorld.class); helloWorld.setMessage(“Hello World!”); helloWorld.getMessage(); } } Once you are done creating all the source files and adding the required additional libraries, let us run the application. You should note that there is no configuration file required. If everything is fine with your application, it will print the following message − Your Message : Hello World! Injecting Bean Dependencies When @Beans have dependencies on one another, expressing that the dependency is as simple as having one bean method calling another as follows − package com.tutorialspoint; import org.springframework.context.annotation.*; @Configuration public class AppConfig { @Bean public Foo foo() { return new Foo(bar()); } @Bean public Bar bar() { return new Bar(); } } Here, the foo bean receives a reference to bar via the constructor injection. Now let us look at another working example. Example Let us have a working Eclipse IDE in place and take the following steps to create a Spring application − Steps Description 1 Create a project with a name SpringExample and create a package com.tutorialspoint under the src folder in the created project. 2 Add required Spring libraries using Add External JARs option as explained in the Spring Hello World Example chapter. 3 Because you are using Java-based annotations, so you also need to add CGLIB.jar from your Java installation directory and ASM.jar library which can be downloaded from asm.ow2.org. 4 Create Java classes TextEditorConfig, TextEditor, SpellChecker and MainApp under the com.tutorialspoint package. 5 The final step is to create the content of all the Java files and Bean Configuration file and run the application as explained below. Here is the content of TextEditorConfig.java file package com.tutorialspoint; import org.springframework.context.annotation.*; @Configuration public class TextEditorConfig { @Bean public TextEditor textEditor(){ return new TextEditor( spellChecker() ); } @Bean public SpellChecker spellChecker(){ return new SpellChecker( ); } } Here is the content of TextEditor.java file package com.tutorialspoint; public class TextEditor { private SpellChecker spellChecker; public TextEditor(SpellChecker spellChecker){ System.out.println(“Inside TextEditor constructor.” ); this.spellChecker = spellChecker; } public void spellCheck(){ spellChecker.checkSpelling(); } } Following is the content of another dependent class file SpellChecker.java package com.tutorialspoint; public class SpellChecker { public SpellChecker(){ System.out.println(“Inside SpellChecker constructor.” ); } public void checkSpelling(){ System.out.println(“Inside checkSpelling.” ); } } Following is the content of the MainApp.java file package com.tutorialspoint; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.*; public class MainApp { public static void main(String[] args) { ApplicationContext ctx = new AnnotationConfigApplicationContext(TextEditorConfig.class); TextEditor te = ctx.getBean(TextEditor.class); te.spellCheck(); } } Once you are done creating all the source files and adding the required additional libraries, let us run the application. You should note that there is no configuration file required. If everything is fine with your application, it will print the following message − Inside SpellChecker constructor. Inside TextEditor constructor. Inside checkSpelling. The @Import Annotation The @Import annotation allows for loading @Bean definitions from another configuration class. Consider a ConfigA class as follows − @Configuration public class ConfigA { @Bean public A a() { return new A(); } } You