Spring – How to do dependency injection in your session listener

Spring comes with a “ContextLoaderListener” listener to enable Spring dependency injection into session listener. In this tutorial, it revises this HttpSessionListener example by adding a Spring dependency injection a bean into the session listener. 1. Spring Beans Create a simple counter service to print total number of sessions created. File : CounterService.java package com.mkyong.common; public …

Read more

How to download J2EE API (javaee.jar) from Maven

This below java.net javaee.jar solution is only contains the J2ee APIs, it does not contain any method bodies. It’s fine for compilation, but not for run or deploy your application, because it will caused ” Absent Code attribute in method that is not native or abstract in class” or other method not found errors. Due …

Read more

Spring MapFactoryBean example

The ‘MapFactoryBean‘ class provides developer a way to create a concrete Map collection class (HashMap and TreeMap) in Spring’s bean configuration file. Here’s a MapFactoryBean example, it will instantiate a HashMap at runtime,, and inject it into a bean property. package com.mkyong.common; import java.util.Map; public class Customer { private Map maps; //… } Spring’s bean …

Read more

Java – Convert Chinese character to Unicode with native2ascii

The native2ascii is a handy tool build-in in the JDK, which is used to convert a file with ‘non-Latin 1’ or ‘non-Unicode’ characters to ‘Unicode-encoded’ characters. Native2ascii example 1. Create a file (source.txt) Create a file named “source.txt”, put some Chinese characters inside, and save it as “UTF-8” format. 2. native2ascii Use native2ascii command to …

Read more

How to display chinese character in Eclipse console

By default, Eclipse will output Chinese or non-English characters as question marks (?) or some weird characters. This is because the Eclipse’s default console encoding is Cp1252 or ASCII, which is unable to display other non-English words. To enable Eclipse to display Chinese or other non-English characters correctly, do following : 1. In Eclipse, right …

Read more

Spring SetFactoryBean example

The ‘SetFactoryBean‘ class provides developer a way to create a concrete Set collection (HashSet and TreeSet) in Spring’s bean configuration file. Here’s a ListFactoryBean example, it will instantiate an HashSet at runtime, and inject it into a bean property package com.mkyong.common; import java.util.Set; public class Customer { private Set sets; //… } Spring’s bean configuration …

Read more

Spring ListFactoryBean example

The ‘ListFactoryBean‘ class provides developer a way to create a concrete List collection class (ArrayList and LinkedList) in Spring’s bean configuration file. Here’s a ListFactoryBean example, it will instantiate an ArrayList at runtime, and inject it into a bean property. package com.mkyong.common; import java.util.List; public class Customer { private List lists; //… } Spring’s bean …

Read more

Spring Collections (List, Set, Map, and Properties) example

Spring examples to show you how to inject values into collections type (List, Set, Map, and Properties). 4 major collection types are supported : List – <list/> Set – <set/> Map – <map/> Properties – <props/> Spring beans A Customer object, with four collection properties. package com.mkyong.common; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; …

Read more

Spring bean configuration inheritance

In Spring, the inheritance is supported in bean configuration for a bean to share common values, properties or configurations. A child bean or inherited bean can inherit its parent bean configurations, properties and some attributes. In additional, the child beans are allow to override the inherited value. See following full example to show you how …

Read more

Spring Auto-Wiring Beans with @Autowired annotation

In last Spring auto-wiring in XML example, it will autowired the matched property of any bean in current Spring container. In most cases, you may need autowired property in a particular bean only. In Spring, you can use @Autowired annotation to auto wire bean on the setter method, constructor or a field. Moreover, it can …

Read more

Spring Auto-Wiring Beans

In Spring framework, you can wire beans automatically with auto-wiring feature. To enable it, just define the “autowire” attribute in <bean>. <bean id="customer" class="com.mkyong.common.Customer" autowire="byName" /> In Spring, 5 Auto-wiring modes are supported. no – Default, no auto wiring, set it manually via “ref” attribute byName – Auto wiring by property name. If the name …

Read more

Spring + JdbcTemplate + JdbcDaoSupport examples

In Spring JDBC development, you can use JdbcTemplate and JdbcDaoSupport classes to simplify the overall database operation processes. In this tutorial, we will reuse the last Spring + JDBC example, to see the different between a before (No JdbcTemplate support) and after (With JdbcTemplate support) example. 1. Example Without JdbcTemplate Witout JdbcTemplate, you have to …

Read more

Spring + JDBC example

In this tutorial, we will extend last Maven + Spring hello world example by adding JDBC support, to use Spring + JDBC to insert a record into a customer table. 1. Customer table In this example, we are using MySQL database. CREATE TABLE `customer` ( `CUST_ID` int(10) unsigned NOT NULL AUTO_INCREMENT, `NAME` varchar(100) NOT NULL, …

Read more

Spring dependency checking with @Required Annotation

Spring’s dependency checking in bean configuration file is used to make sure all properties of a certain types (primitive, collection or object) have been set. In most scenarios, you just need to make sure a particular property has been set, but not all properties.. For this case, you need @Required annotation, see following example : …

Read more

How to Get Current Timestamps in Java

This article shows how to get the current date time or timestamps in Java. import java.sql.Timestamp; import java.time.Instant; import java.util.Date; // 2025-03-07 21:34:46.504 // Get current java.sql.Timestamp Timestamp timestamp = new Timestamp(System.currentTimeMillis()); // 2025-03-07 21:34:46.504 // Get current java.sql.Timestamp from a Date Date date = new Date(); Timestamp timestamp2 = new Timestamp(date.getTime()); // convert Instant …

Read more

Spring properties dependency checking

In Spring,you can use dependency checking feature to make sure the required properties have been set or injected. Dependency checking modes 4 dependency checking modes are supported: none – No dependency checking. simple – If any properties of primitive type (int, long,double…) and collection types (map, list..) have not been set, UnsatisfiedDependencyException will be thrown. …

Read more

Hibernate Error – java.lang.NoClassDefFoundError: javax/transaction/Synchronization

Problem This is caused by missing of the “jta.jar“, usually happened in Hibernate transaction development. java.lang.NoClassDefFoundError: javax/transaction/Synchronization at org.hibernate.impl.SessionImpl.<init>(SessionImpl.java:213) at org.hibernate.impl.SessionFactoryImpl.openSession(SessionFactoryImpl.java:473) at org.hibernate.impl.SessionFactoryImpl.openSession(SessionFactoryImpl.java:497) at org.hibernate.impl.SessionFactoryImpl.openSession(SessionFactoryImpl.java:505) at com.mkyong.common.App.main(App.java:13) Caused by: java.lang.ClassNotFoundException: javax.transaction.Synchronization at java.net.URLClassLoader$1.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at java.lang.ClassLoader.loadClassInternal(Unknown Source) … 5 more …

Read more

Spring inner bean examples

In Spring framework, whenever a bean is used for only one particular property, it’s advise to declare it as an inner bean. And the inner bean is supported both in setter injection ‘property‘ and constructor injection ‘constructor-arg‘. See a detail example to demonstrate the use of Spring inner bean. package com.mkyong.common; public class Customer { …

Read more

Constructor injection type ambiguities in Spring

In Spring framework, when your class contains multiple constructors with same number of arguments, it will always cause the constructor injection argument type ambiguities issue. Problem Let’s see this customer bean example. It contains two constructor methods, both accept 3 arguments with different data type. package com.mkyong.common; public class Customer { private String name; private …

Read more

Spring Dependency Injection (DI)

In Spring frameowork, Dependency Injection (DI) design pattern is used to define the object dependencies between each other. It exits in two major types : Setter Injection Constructor Injection 1. Setter Injection This is the most popular and simple DI method, it will injects the dependency via a setter method. Example A helper class with …

Read more

Spring bean reference example

In Spring, beans can “access” to each other by specify the bean references in the same or different bean configuration file. 1. Bean in different XML files If you are referring to a bean in different XML file, you can reference it with a ‘ref‘ tag, ‘bean‘ attribute. <ref bean="someBean"/> In this example, the bean …

Read more

How to inject value into bean properties in Spring

In Spring, there are three ways to inject value into bean properties. Normal way Shortcut “p” schema See a simple Java class, which contains two properties – name and type. Later you will use Spring to inject value into the bean properties. package com.mkyong.common; public class FileNameGenerator { private String name; private String type; public …

Read more

How to install Spring IDE in Eclipse

Spring IDE is a very useful graphical user interface tool adding support for Spring Framework. In this tutorial, we show you two ways to install Spring IDE in Eclipse. Version used in this tutorial : Spring IDE 2.9 Eclipse 3.7 Spring IDE or SpringSource Tool Suite (STS)? Refer to this Spring IDE vs STS pdf …

Read more

Spring loosely coupled example

The concept of object-oriented is a good design to break your system into a group of reusable objects. However, when system grows larger, especially in Java project, the huge object dependencies will always tightly coupled causing objects very hard to manage or modify. In this scenario, you can use Spring framework to act as a …

Read more

How to load multiple Spring bean configuration file

Problem In a large project structure, the Spring’s bean configuration files are located in different folders for easy maintainability and modular. For example, Spring-Common.xml in common folder, Spring-Connection.xml in connection folder, Spring-ModuleA.xml in ModuleA folder…and etc. You may load multiple Spring bean configuration files in the code : ApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"Spring-Common.xml", …

Read more

Maven + Spring hello world example

This quick guide example uses Maven to generate a simple Java project structure, and demonstrates how to retrieve Spring bean and prints a “hello world” string. Technologies used in this article : Spring 2.5.6 Maven 3.0.3 Eclipse 3.6 JDK 1.6.0.13 Spring 3 example For Spring 3, refer to this Maven + Spring 3 hello world …

Read more

How to change Maven resources folder location?

Maven resources folder is used to store all your project resources files like , xml files, images, text files and etc. The default Maven resources folder is located at “yourproject/src/main/resources“. Problem In some projects’ structure, the default resource folder may not suit in your needs, and an additional resource folder may required. Solution You can …

Read more

Java SHA-256 and SHA3-256 Hashing Example

In Java, we can use MessageDigest to get a SHA-256 or SHA3-256 hashing algorithm to hash a string. MessageDigest md = MessageDigest.getInstance("SHA3-256"); byte[] result = md.digest(input); This article shows how to use Java SHA-256 and SHA3-256 algorithms to generate a hash value from a given string and checksum from a file. Note The hashing is …

Read more

Java MD5 Hashing Example

The MD5, defined in RFC 1321, is a hash algorithm to turn inputs into a fixed 128-bit (16 bytes) length of the hash value. Note MD5 is not collision-resistant – Two different inputs may producing the same hash value. Read this MD5 vulnerabilities. There are many fast and secure hashing algorithms like SHA3-256 or BLAKE2; …

Read more

Hibernate – fetching strategies examples

Hibernate has few fetching strategies to optimize the Hibernate generated select statement, so that it can be as efficient as possible. The fetching strategy is declared in the mapping relationship to define how Hibernate fetch its related collections and entities. Fetching Strategies There are four fetching strategies 1. fetch-“join” = Disable the lazy loading, always …

Read more

Hibernate Criteria examples

Hibernate Criteria API is a more object oriented and elegant alternative to Hibernate Query Language (HQL). It’s always a good solution to an application which has many optional search criteria. Example in HQL and Criteria Here’s a case study to retrieve a list of StockDailyRecord, with optional search criteria – start date, end date and …

Read more

Hibernate interceptor example – audit log

Hibernate has a powerful feature called ‘interceptor‘ to intercept or hook different kind of Hibernate events, like database CRUD operation. In this article, i will demonstrate how to implement an application audit log feature by using Hibernate interceptor, it will log all the Hibernate save, update or delete operations into a database table named ‘auditlog‘. …

Read more

Hibernate mutable example (class and collection)

In hibernate, ‘mutable‘ is default to ‘true’ in class and its related collection, it mean the class or collection are allow to add, update and delete. On the other hand, if the mutable is changed to false, it has different meaning in class and its related collection. Let’s take some examples to understand more about …

Read more

How to embed Oracle hints in Hibernate query

With Oracle hints, you can alter the Oracle execution plans to affect the way how Oracle retrieve the data from database. Go here for more detail about Oracle optimizer hints. In Hibernate, is this possible to embed the Oracle hint into the Hibernate query? Hibernate setComment()? Can you embed the Oracle hint into HQL with …

Read more

How to call stored procedure in Hibernate

In this tutorial, you will learn how to call a store procedure in Hibernate. MySQL store procedure Here’s a MySQL store procedure, which accept a stock code parameter and return the related stock data. DELIMITER $$ CREATE PROCEDURE `GetStocks`(int_stockcode varchar(20)) BEGIN SELECT * FROM stock where stock_code = int_stockcode; END $$ DELIMITER ; In MySQL, …

Read more

Hibernate parameter binding examples

Without parameter binding, you have to concatenate the parameter String like this (bad code) : String hql = "from Stock s where s.stockCode = ‘" + stockCode + "’"; List result = session.createQuery(hql).list(); Pass an unchecked value from user input to the database will raise security concern, because it can easy get hack by SQL …

Read more

Hibernate native SQL queries examples

In Hibernate, HQL or criteria queries should be able to let you to execute almost any SQL query you want. However, many developers are complaint about the Hibernate’s generated SQL statement is slow and more prefer to generated their own SQL (native SQL) statement. Native SQL queries example Hibernate provide a createSQLQuery method to let …

Read more

Hibernate named query examples

Often times, developer like to put HQL string literals scatter all over the Java code, this method is hard to maintaine and look ugly. Fortunately, Hibernate come out a technique called “names queries” , it lets developer to put all HQL into the XML mapping file or via annotation. How to declare named query The …

Read more

Hibernate Query examples (HQL)

Hibernate created a new language named Hibernate Query Language (HQL), the syntax is quite similar to database SQL language. The main difference between is HQL uses class name instead of table name, and property names instead of column name. HQL is extremely simple to learn and use, and the code is always self-explanatory. 1. HQL …

Read more