Spring – AOP with Spring Framework

AOP with Spring Framework ”; Previous Next One of the key components of Spring Framework is the Aspect oriented programming (AOP) framework. Aspect-Oriented Programming entails breaking down program logic into distinct parts called so-called concerns. The functions that span multiple points of an application are called cross-cutting concerns and these cross-cutting concerns are conceptually separate from the application”s business logic. There are various common good examples of aspects like logging, auditing, declarative transactions, security, caching, etc. The key unit of modularity in OOP is the class, whereas in AOP the unit of modularity is the aspect. Dependency Injection helps you decouple your application objects from each other and AOP helps you decouple cross-cutting concerns from the objects that they affect. AOP is like triggers in programming languages such as Perl, .NET, Java, and others. Spring AOP module provides interceptors to intercept an application. For example, when a method is executed, you can add extra functionality before or after the method execution. AOP Terminologies Before we start working with AOP, let us become familiar with the AOP concepts and terminology. These terms are not specific to Spring, rather they are related to AOP. Sr.No Terms & Description 1 Aspect This is a module which has a set of APIs providing cross-cutting requirements. For example, a logging module would be called AOP aspect for logging. An application can have any number of aspects depending on the requirement. 2 Join point This represents a point in your application where you can plug-in the AOP aspect. You can also say, it is the actual place in the application where an action will be taken using Spring AOP framework. 3 Advice This is the actual action to be taken either before or after the method execution. This is an actual piece of code that is invoked during the program execution by Spring AOP framework. 4 Pointcut This is a set of one or more join points where an advice should be executed. You can specify pointcuts using expressions or patterns as we will see in our AOP examples. 5 Introduction An introduction allows you to add new methods or attributes to the existing classes. 6 Target object The object being advised by one or more aspects. This object will always be a proxied object, also referred to as the advised object. 7 Weaving Weaving is the process of linking aspects with other application types or objects to create an advised object. This can be done at compile time, load time, or at runtime. Types of Advice Spring aspects can work with five kinds of advice mentioned as follows − Sr.No Advice & Description 1 before Run advice before the a method execution. 2 after Run advice after the method execution, regardless of its outcome. 3 after-returning Run advice after the a method execution only if method completes successfully. 4 after-throwing Run advice after the a method execution only if method exits by throwing an exception. 5 around Run advice before and after the advised method is invoked. Custom Aspects Implementation Spring supports the @AspectJ annotation style approach and the schema-based approach to implement custom aspects. These two approaches have been explained in detail in the following sections. Sr.No Approach & Description 1 XML Schema based Aspects are implemented using the regular classes along with XML based configuration. 2 @AspectJ based @AspectJ refers to a style of declaring aspects as regular Java classes annotated with Java 5 annotations. Print Page Previous Next Advertisements ”;

Spring – JDBC Framework

Spring – JDBC Framework Overview ”; Previous Next While working with the database using plain old JDBC, it becomes cumbersome to write unnecessary code to handle exceptions, opening and closing database connections, etc. However, Spring JDBC Framework takes care of all the low-level details starting from opening the connection, prepare and execute the SQL statement, process exceptions, handle transactions and finally close the connection. So what you have to do is just define the connection parameters and specify the SQL statement to be executed and do the required work for each iteration while fetching data from the database. Spring JDBC provides several approaches and correspondingly different classes to interface with the database. I”m going to take classic and the most popular approach which makes use of JdbcTemplate class of the framework. This is the central framework class that manages all the database communication and exception handling. JdbcTemplate Class The JDBC Template class executes SQL queries, updates statements, stores procedure calls, performs iteration over ResultSets, and extracts returned parameter values. It also catches JDBC exceptions and translates them to the generic, more informative, exception hierarchy defined in the org.springframework.dao package. Instances of the JdbcTemplate class are threadsafe once configured. So you can configure a single instance of a JdbcTemplate and then safely inject this shared reference into multiple DAOs. A common practice when using the JDBC Template class is to configure a DataSource in your Spring configuration file, and then dependency-inject that shared DataSource bean into your DAO classes, and the JdbcTemplate is created in the setter for the DataSource. Configuring Data Source Let us create a database table Student in our database TEST. We assume you are working with MySQL database, if you work with any other database then you can change your DDL and SQL queries accordingly. CREATE TABLE Student( ID INT NOT NULL AUTO_INCREMENT, NAME VARCHAR(20) NOT NULL, AGE INT NOT NULL, PRIMARY KEY (ID) ); Now we need to supply a DataSource to the JDBC Template so it can configure itself to get database access. You can configure the DataSource in the XML file with a piece of code as shown in the following code snippet − <bean id = “dataSource” class = “org.springframework.jdbc.datasource.DriverManagerDataSource”> <property name = “driverClassName” value = “com.mysql.jdbc.Driver”/> <property name = “url” value = “jdbc:mysql://localhost:3306/TEST”/> <property name = “username” value = “root”/> <property name = “password” value = “password”/> </bean> Data Access Object (DAO) DAO stands for Data Access Object, which is commonly used for database interaction. DAOs exist to provide a means to read and write data to the database and they should expose this functionality through an interface by which the rest of the application will access them. The DAO support in Spring makes it easy to work with data access technologies like JDBC, Hibernate, JPA, or JDO in a consistent way. Executing SQL statements Let us see how we can perform CRUD (Create, Read, Update and Delete) operation on database tables using SQL and JDBC Template object. Querying for an integer String SQL = “select count(*) from Student”; int rowCount = jdbcTemplateObject.queryForInt( SQL ); Querying for a long String SQL = “select count(*) from Student”; long rowCount = jdbcTemplateObject.queryForLong( SQL ); A simple query using a bind variable String SQL = “select age from Student where id = ?”; int age = jdbcTemplateObject.queryForInt(SQL, new Object[]{10}); Querying for a String String SQL = “select name from Student where id = ?”; String name = jdbcTemplateObject.queryForObject(SQL, new Object[]{10}, String.class); Querying and returning an object String SQL = “select * from Student where id = ?”; Student student = jdbcTemplateObject.queryForObject( SQL, new Object[]{10}, new StudentMapper()); public class StudentMapper implements RowMapper<Student> { public Student mapRow(ResultSet rs, int rowNum) throws SQLException { Student student = new Student(); student.setID(rs.getInt(“id”)); student.setName(rs.getString(“name”)); student.setAge(rs.getInt(“age”)); return student; } } Querying and returning multiple objects String SQL = “select * from Student”; List<Student> students = jdbcTemplateObject.query( SQL, new StudentMapper()); public class StudentMapper implements RowMapper<Student> { public Student mapRow(ResultSet rs, int rowNum) throws SQLException { Student student = new Student(); student.setID(rs.getInt(“id”)); student.setName(rs.getString(“name”)); student.setAge(rs.getInt(“age”)); return student; } } Inserting a row into the table String SQL = “insert into Student (name, age) values (?, ?)”; jdbcTemplateObject.update( SQL, new Object[]{“Zara”, 11} ); Updating a row into the table String SQL = “update Student set name = ? where id = ?”; jdbcTemplateObject.update( SQL, new Object[]{“Zara”, 10} ); Deleting a row from the table String SQL = “delete Student where id = ?”; jdbcTemplateObject.update( SQL, new Object[]{20} ); Executing DDL Statements You can use the execute(..) method from jdbcTemplate to execute any SQL statements or DDL statements. Following is an example to use CREATE statement to create a table − String SQL = “CREATE TABLE Student( ” + “ID INT NOT NULL AUTO_INCREMENT, ” + “NAME VARCHAR(20) NOT NULL, ” + “AGE INT NOT NULL, ” + “PRIMARY KEY (ID));” jdbcTemplateObject.execute( SQL ); Spring JDBC Framework Examples Based on the above concepts, let us check few important examples which will help you in understanding usage of JDBC framework in Spring − Sr.No. Example & Description 1 Spring JDBC Example This example will explain how to write a simple JDBC-based Spring application. 2 SQL Stored Procedure in Spring Learn how to call SQL stored procedure while using JDBC in Spring. Print Page Previous Next Advertisements ”;

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

Spring – IoC Containers

Spring – IoC Containers ”; Previous Next The Spring container is at the core of the Spring Framework. The container will create the objects, wire them together, configure them, and manage their complete life cycle from creation till destruction. The Spring container uses DI to manage the components that make up an application. These objects are called Spring Beans, which we will discuss in the next chapter. The container gets its instructions on what objects to instantiate, configure, and assemble by reading the configuration metadata provided. The configuration metadata can be represented either by XML, Java annotations, or Java code. The following diagram represents a high-level view of how Spring works. The Spring IoC container makes use of Java POJO classes and configuration metadata to produce a fully configured and executable system or application. Spring provides the following two distinct types of containers. Sr.No. Container & Description 1 Spring BeanFactory Container This is the simplest container providing the basic support for DI and is defined by the org.springframework.beans.factory.BeanFactory interface. The BeanFactory and related interfaces, such as BeanFactoryAware, InitializingBean, DisposableBean, are still present in Spring for the purpose of backward compatibility with a large number of third-party frameworks that integrate with Spring. 2 Spring ApplicationContext Container This container adds more enterprise-specific functionality such as the ability to resolve textual messages from a properties file and the ability to publish application events to interested event listeners. This container is defined by the org.springframework.context.ApplicationContext interface. The ApplicationContext container includes all functionality of the BeanFactorycontainer, so it is generally recommended over BeanFactory. BeanFactory can still be used for lightweight applications like mobile devices or applet-based applications where data volume and speed is significant. Print Page Previous Next Advertisements ”;

Annotation Based Configuration

Spring – Annotation Based Configuration ”; Previous Next Starting from Spring 2.5 it became possible to configure the dependency injection using annotations. So instead of using XML to describe a bean wiring, you can move the bean configuration into the component class itself by using annotations on the relevant class, method, or field declaration. Annotation injection is performed before XML injection. Thus, the latter configuration will override the former for properties wired through both approaches. Annotation wiring is not turned on in the Spring container by default. So, before we can use annotation-based wiring, we will need to enable it in our Spring configuration file. So consider the following configuration file in case you want to use any annotation in your Spring application. <?xml version = “1.0” encoding = “UTF-8”?> <beans xmlns = “http://www.springframework.org/schema/beans” xmlns:xsi = “http://www.w3.org/2001/XMLSchema-instance” xmlns:context = “http://www.springframework.org/schema/context” 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:annotation-config/> <!– bean definitions go here –> </beans> Once <context:annotation-config/> is configured, you can start annotating your code to indicate that Spring should automatically wire values into properties, methods, and constructors. Let us look at a few important annotations to understand how they work − Sr.No. Annotation & Description 1 @Required The @Required annotation applies to bean property setter methods. 2 @Autowired The @Autowired annotation can apply to bean property setter methods, non-setter methods, constructor and properties. 3 @Qualifier The @Qualifier annotation along with @Autowired can be used to remove the confusion by specifiying which exact bean will be wired. 4 JSR-250 Annotations Spring supports JSR-250 based annotations which include @Resource, @PostConstruct and @PreDestroy annotations. Print Page Previous Next Advertisements ”;

Spring – Useful Resources

Spring – Useful Resources ”; Previous Next The following resources contain additional information on Spring. Please use them to get more in-depth knowledge on this topic. Useful Video Courses Spring Framework Mastery Course Best Seller 103 Lectures 8 hours Karthikeya T More Detail JWT Role-Based Authorization With Spring Boot and Angular 8 54 Lectures 3.5 hours Senol Atac More Detail Learn Spring Core Framework the Easy Way! 82 Lectures 5 hours Karthikeya T More Detail Spring MVC Essentials: A Primary Course for Java Spring MVC 25 Lectures 3.5 hours TELCOMA Global More Detail Spring Core (Spring Framework): An In-Depth Hands-on Guide 28 Lectures 4.5 hours TELCOMA Global More Detail Java Spring Framework 5 – Build A Web App Step By Step Best Seller 122 Lectures 11 hours Damian Jedrzejak More Detail Print Page Previous Next Advertisements ”;

Spring – Custom Events in Spring

Custom Events in Spring ”; Previous Next There are number of steps to be taken to write and publish your own custom events. Follow the instructions given in this chapter to write, publish and handle Custom Spring Events. Steps Description 1 Create a project with a name SpringExample and create a package com.tutorialspoint under the src folder in the created project. All the classes will be created under this package. 2 Add required Spring libraries using Add External JARs option as explained in the Spring Hello World Example chapter. 3 Create an event class, CustomEvent by extending ApplicationEvent. This class must define a default constructor which should inherit constructor from ApplicationEvent class. 4 Once your event class is defined, you can publish it from any class, let us say EventClassPublisher which implements ApplicationEventPublisherAware. You will also need to declare this class in XML configuration file as a bean so that the container can identify the bean as an event publisher because it implements the ApplicationEventPublisherAware interface. 5 A published event can be handled in a class, let us say EventClassHandler which implements ApplicationListener interface and implements onApplicationEvent method for the custom event. 6 Create beans configuration file Beans.xml under the src folder and a MainApp class which will work as Spring application. 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 CustomEvent.java file package com.tutorialspoint; import org.springframework.context.ApplicationEvent; public class CustomEvent extends ApplicationEvent{ public CustomEvent(Object source) { super(source); } public String toString(){ return “My Custom Event”; } } Following is the content of the CustomEventPublisher.java file package com.tutorialspoint; import org.springframework.context.ApplicationEventPublisher; import org.springframework.context.ApplicationEventPublisherAware; public class CustomEventPublisher implements ApplicationEventPublisherAware { private ApplicationEventPublisher publisher; public void setApplicationEventPublisher (ApplicationEventPublisher publisher) { this.publisher = publisher; } public void publish() { CustomEvent ce = new CustomEvent(this); publisher.publishEvent(ce); } } Following is the content of the CustomEventHandler.java file package com.tutorialspoint; import org.springframework.context.ApplicationListener; public class CustomEventHandler implements ApplicationListener<CustomEvent> { public void onApplicationEvent(CustomEvent event) { System.out.println(event.toString()); } } Following is the content of the MainApp.java file package com.tutorialspoint; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class MainApp { public static void main(String[] args) { ConfigurableApplicationContext context = new ClassPathXmlApplicationContext(“Beans.xml”); CustomEventPublisher cvp = (CustomEventPublisher) context.getBean(“customEventPublisher”); cvp.publish(); cvp.publish(); } } Following is the configuration file Beans.xml <?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 = “customEventHandler” class = “com.tutorialspoint.CustomEventHandler”/> <bean id = “customEventPublisher” class = “com.tutorialspoint.CustomEventPublisher”/> </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 − y Custom Event y Custom Event Print Page Previous Next Advertisements ”;

Spring – Beans Auto-Wiring

Spring – Beans Auto-Wiring ”; Previous Next You have learnt how to declare beans using the <bean> element and inject <bean> using <constructor-arg> and <property> elements in XML configuration file. The Spring container can autowire relationships between collaborating beans without using <constructor-arg> and <property> elements, which helps cut down on the amount of XML configuration you write for a big Spring-based application. Autowiring Modes Following are the autowiring modes, which can be used to instruct the Spring container to use autowiring for dependency injection. You use the autowire attribute of the <bean/> element to specify autowire mode for a bean definition. Sr.No Mode & Description 1 no This is default setting which means no autowiring and you should use explicit bean reference for wiring. You have nothing to do special for this wiring. This is what you already have seen in Dependency Injection chapter. 2 byName Autowiring by property name. Spring container looks at the properties of the beans on which autowire attribute is set to byName in the XML configuration file. It then tries to match and wire its properties with the beans defined by the same names in the configuration file. 3 byType Autowiring by property datatype. Spring container looks at the properties of the beans on which autowire attribute is set to byType in the XML configuration file. It then tries to match and wire a property if its type matches with exactly one of the beans name in configuration file. If more than one such beans exists, a fatal exception is thrown. 4 constructor Similar to byType, but type applies to constructor arguments. If there is not exactly one bean of the constructor argument type in the container, a fatal error is raised. 5 autodetect Spring first tries to wire using autowire by constructor, if it does not work, Spring tries to autowire by byType. You can use byType or constructor autowiring mode to wire arrays and other typed-collections. Limitations with autowiring Autowiring works best when it is used consistently across a project. If autowiring is not used in general, it might be confusing for developers to use it to wire only one or two bean definitions. Though, autowiring can significantly reduce the need to specify properties or constructor arguments but you should consider the limitations and disadvantages of autowiring before using them. Sr.No. Limitations & Description 1 Overriding possibility You can still specify dependencies using <constructor-arg> and <property> settings which will always override autowiring. 2 Primitive data types You cannot autowire so-called simple properties such as primitives, Strings, and Classes. 3 Confusing nature Autowiring is less exact than explicit wiring, so if possible prefer using explict wiring. Print Page Previous Next Advertisements ”;

Spring – Bean Life Cycle

Spring – Bean Life Cycle ”; Previous Next The life cycle of a Spring bean is easy to understand. When a bean is instantiated, it may be required to perform some initialization to get it into a usable state. Similarly, when the bean is no longer required and is removed from the container, some cleanup may be required. Though, there are lists of the activities that take place behind the scene between the time of bean Instantiation and its destruction, this chapter will discuss only two important bean life cycle callback methods, which are required at the time of bean initialization and its destruction. To define setup and teardown for a bean, we simply declare the <bean> with initmethod and/or destroy-method parameters. The init-method attribute specifies a method that is to be called on the bean immediately upon instantiation. Similarly, destroymethod specifies a method that is called just before a bean is removed from the container. Initialization callbacks The org.springframework.beans.factory.InitializingBean interface specifies a single method − void afterPropertiesSet() throws Exception; Thus, you can simply implement the above interface and initialization work can be done inside afterPropertiesSet() method as follows − public class ExampleBean implements InitializingBean { public void afterPropertiesSet() { // do some initialization work } } In the case of XML-based configuration metadata, you can use the init-method attribute to specify the name of the method that has a void no-argument signature. For example − <bean id = “exampleBean” class = “examples.ExampleBean” init-method = “init”/> Following is the class definition − public class ExampleBean { public void init() { // do some initialization work } } Destruction callbacks The org.springframework.beans.factory.DisposableBean interface specifies a single method − void destroy() throws Exception; Thus, you can simply implement the above interface and finalization work can be done inside destroy() method as follows − public class ExampleBean implements DisposableBean { public void destroy() { // do some destruction work } } In the case of XML-based configuration metadata, you can use the destroy-method attribute to specify the name of the method that has a void no-argument signature. For example − <bean id = “exampleBean” class = “examples.ExampleBean” destroy-method = “destroy”/> Following is the class definition − public class ExampleBean { public void destroy() { // do some destruction work } } If you are using Spring”s IoC container in a non-web application environment; for example, in a rich client desktop environment, you register a shutdown hook with the JVM. Doing so ensures a graceful shutdown and calls the relevant destroy methods on your singleton beans so that all resources are released. It is recommended that you do not use the InitializingBean or DisposableBean callbacks, because XML configuration gives much flexibility in terms of naming your method. 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 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.”); } } 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 ensure a graceful shutdown and call 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> </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 − Bean is going through init. Your Message : Hello World! Bean will destroy now. Default initialization and destroy methods If you have too many beans having initialization and/or destroy methods with the same name, you don”t need to declare init-method and destroy-method on each individual bean. Instead, the framework provides the flexibility to configure such situation using default-init-method and default-destroy-method attributes on the <beans> element as follows − <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” default-init-method = “init” default-destroy-method = “destroy”> <bean id = “…” class = “…”> <!– collaborators and configuration for this bean go here –> </bean> </beans> Print Page Previous Next Advertisements ”;

Spring – Environment Setup

Spring – Environment Setup ”; Previous Next This chapter will guide you on how to prepare a development environment to start your work with Spring Framework. It will also teach you how to set up JDK, Tomcat and Eclipse on your machine before you set up Spring Framework − Step 1 – Setup Java Development Kit (JDK) You can download the latest version of SDK from Oracle”s Java site − Java SE Downloads. You will find instructions for installing JDK in downloaded files, follow the given instructions to install and configure the setup. Finally set PATH and JAVA_HOME environment variables to refer to the directory that contains java and javac, typically java_install_dir/bin and java_install_dir respectively. If you are running Windows and have installed the JDK in C:jdk1.6.0_15, you would have to put the following line in your C:autoexec.bat file. set PATH=C:jdk1.6.0_15bin;%PATH% set JAVA_HOME=C:jdk1.6.0_15 Alternatively, on Windows NT/2000/XP, you will have to right-click on My Computer, select Properties → Advanced → Environment Variables. Then, you will have to update the PATH value and click the OK button. On Unix (Solaris, Linux, etc.), if the SDK is installed in /usr/local/jdk1.6.0_15 and you use the C shell, you will have to put the following into your .cshrc file. setenv PATH /usr/local/jdk1.6.0_15/bin:$PATH setenv JAVA_HOME /usr/local/jdk1.6.0_15 Alternatively, if you use an Integrated Development Environment (IDE) like Borland JBuilder, Eclipse, IntelliJ IDEA, or Sun ONE Studio, you will have to compile and run a simple program to confirm that the IDE knows where you have installed Java. Otherwise, you will have to carry out a proper setup as given in the document of the IDE. Step 2 – Install Apache Common Logging API You can download the latest version of Apache Commons Logging API from https://commons.apache.org/logging/. Once you download the installation, unpack the binary distribution into a convenient location. For example, in C:commons-logging-1.1.1 on Windows, or /usr/local/commons-logging-1.1.1 on Linux/Unix. This directory will have the following jar files and other supporting documents, etc. Make sure you set your CLASSPATH variable on this directory properly otherwise you will face a problem while running your application. Step 3 – Setup Eclipse IDE All the examples in this tutorial have been written using Eclipse IDE. So we would suggest you should have the latest version of Eclipse installed on your machine. To install Eclipse IDE, download the latest Eclipse binaries from https://www.eclipse.org/downloads/. Once you download the installation, unpack the binary distribution into a convenient location. For example, in C:eclipse on Windows, or /usr/local/eclipse on Linux/Unix and finally set PATH variable appropriately. Eclipse can be started by executing the following commands on Windows machine, or you can simply double-click on eclipse.exe %C:eclipseeclipse.exe Eclipse can be started by executing the following commands on Unix (Solaris, Linux, etc.) machine − $/usr/local/eclipse/eclipse After a successful startup, if everything is fine then it should display the following result − Step 4 – Setup Spring Framework Libraries Now if everything is fine, then you can proceed to set up your Spring framework. Following are the simple steps to download and install the framework on your machine. Make a choice whether you want to install Spring on Windows or Unix, and then proceed to the next step to download .zip file for Windows and .tz file for Unix. Download the latest version of Spring framework binaries from https://repo.spring.io/release/org/springframework/spring. At the time of developing this tutorial, spring-framework-4.1.6.RELEASE-dist.zip was downloaded on Windows machine. After the downloaded file was unzipped, it gives the following directory structure inside E:spring. You will find all the Spring libraries in the directory E:springlibs. Make sure you set your CLASSPATH variable on this directory properly otherwise you will face a problem while running your application. If you are using Eclipse, then it is not required to set CLASSPATH because all the setting will be done through Eclipse. Once you are done with this last step, you are ready to proceed to your first Spring Example in the next chapter. Print Page Previous Next Advertisements ”;