In Spring AOP, you have to include the cglib library into your build path to avoid the “Cannot proxy target class because CGLIB2 is not available” error message. Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘customerServiceProxy’: FactoryBean threw exception on object creation; nested exception is org.springframework.aop.framework.AopConfigException: Cannot proxy target class because CGLIB2 […]

Read more Spring AOP Error : Cannot proxy target class because CGLIB2 is not available

Spring JdbcTemplate batch insert, batch update and also @Transactional examples. Technologies used : Spring Boot 2.1.2.RELEASE Spring JDBC 5.1.4.RELEASE Maven 3 Java 8 1. Batch Insert 1.1 Insert a batch of SQL Inserts together. BookRepository.java import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.BatchPreparedStatementSetter; public int[] batchInsert(List<Book> books) { return this.jdbcTemplate.batchUpdate( "insert into books (name, price) values(?,?)", new BatchPreparedStatementSetter() { […]

Read more Spring JdbcTemplate batchUpdate() Example

Spring example to show you how to inject a “Date” into bean property. package com.mkyong.common; import java.util.Date; public class Customer { Date date; public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } @Override public String toString() { return "Customer [date=" + date + "]"; } } Bean configuration […]

Read more Spring inject Date into bean property – CustomDateEditor

In last tutorial, you are able to get the MessageSource via ApplicationContext. But for a bean to get the MessageSource, you have to implement the MessageSourceAware interface. Example A CustomerService class, implement the MessageSourceAware interface, has a setter method to set the MessageSource property. During Spring container initialization, if any class which implements the MessageSourceAware […]

Read more Spring – How to access MessageSource in bean (MessageSourceAware)

Problem The ContextLoaderListener is used to integrate Spring with other web application. <!– file : web.xml –> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/Spring/applicationContext.xml</param-value> </context-param> <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener> And the common error message is, your server can not find this Spring ContextLoaderListener class during the server start up. SEVERE: Error configuring application listener of class org.springframework.web.context.ContextLoaderListener java.lang.ClassNotFoundException: […]

Read more ClassNotFoundException : org.springframework.web.context.ContextLoaderListener

The @Required annotation is used to make sure a particular property has been set. If you are migrate your existing project to Spring framework or have your own @Required-style annotation for whatever reasons, Spring is allow you to define your custom @Required-style annotation, which is equivalent to @Required annotation. In this example, you will create […]

Read more Define custom @Required-style annotation in Spring

In Spring, you can use ResourceBundleMessageSource to resolve text messages from properties file, base on the selected locales. See following example : 1. Directory Structure Review directory structure of this example. 2. Properties file Create two properties files, one for English characters (messages_en_US.properties), other one for Chinese characters (messages_zh_CN.properties). Put it into the project class […]

Read more Spring Resource bundle with ResourceBundleMessageSource example

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 Spring – How to do dependency injection in your session listener

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 Spring MapFactoryBean example

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 Java – Convert Chinese character to Unicode with native2ascii

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 How to display chinese character in Eclipse console

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 SetFactoryBean 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 ListFactoryBean 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 Collections (List, Set, Map, and Properties) example

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 bean configuration inheritance

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 with @Autowired annotation

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 Auto-Wiring Beans

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 + JdbcTemplate + JdbcDaoSupport examples

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 + JDBC example

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 Spring dependency checking with @Required Annotation

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 How to Get Current Timestamps in Java

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 Spring properties dependency checking

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 Hibernate Error – java.lang.NoClassDefFoundError: javax/transaction/Synchronization

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 Spring inner bean examples

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 Constructor injection type ambiguities 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 inject value into bean properties in Spring

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 How to load multiple Spring bean configuration file

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 How to change Maven resources folder location?

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 SHA-256 and SHA3-256 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 Java MD5 Hashing Example

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 – fetching strategies examples

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 interceptor example – audit log

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 Hibernate mutable example (class and collection)