Quartz 1.6 scheduler tutorial

Quartz is a powerful and advance scheduler framework, to help Java developer to scheduler a job to run at a specified date and time. This tutorial show you how to develop a scheduler job using Quartz 1.6.3. Note This example is a bit outdate, unless you are still using the old Quartz 1.6.3 library, otherwise, …

Read more

Spring + JDK Timer scheduler example

Note Learn the JDK Timer scheduler example without Spring and compare the different with this example. In this example, you will use Spring’s Scheduler API to schedule a task. 1. Scheduler Task Create a scheduler task… package com.mkyong.common; public class RunMeTask { public void printMe() { System.out.println("Run Me ~"); } } <bean id="runMeTask" class="com.mkyong.common.RunMeTask" /> …

Read more

TestNG Tutorial

TestNG tutorial with full example, introduce the TestNG basic usage, annotation support, and test case for expected exception test, ignore test, time test, suite test, parameterized test, dependency test and etc

JDK Timer scheduler example

JDK Timer is a simple scheduler for a specified task for repeated fixed-delay execution. To use this, you have to extends the TimerTask abstract class, override the run() method with your scheduler function. RunMeTask.java package com.mkyong.common; import java.util.TimerTask; public class RunMeTask extends TimerTask { @Override public void run() { System.out.println("Run Me ~"); } } Now, …

Read more

Maven + (Spring + Hibernate) Annotation + MySql Example

Download It – Spring-Hibernate-Annotation-Example.zip In last tutorial, you use Maven to create a simple Java project structure, and demonstrate how to use Hibernate in Spring framework to do the data manipulation works(insert, select, update and delete) in MySQL database. In this tutorial, you will learn how to do the same thing in Spring and Hibernate …

Read more

Spring Resource loader with getResource() example

Spring’s resource loader provides a very generic getResource() method to get the resources like (text file, media file, image file…) from file system , classpath or URL. You can get the getResource() method from the application context. Here’s an example to show how to use getResource() to load a text file from 1. File system …

Read more

Spring – Sending e-mail with attachment

Here’s an example to use Spring to send e-mail that has attachments via Gmail SMTP server. In order to contains the attachment in your e-mail, you have to use Spring’s JavaMailSender & MimeMessage , instead of MailSender & SimpleMailMessage. 1. Project dependency Add the JavaMail and Spring’s dependency. File : pom.xml <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 …

Read more

Spring – Define an E-mail template in bean configuration file

In last Spring’s email tutorial, you hard-code all the email properties and message content in the method body, it’s not practical and should be avoid. You should consider define the email message template in the Spring’s bean configuration file. 1. Project dependency Add the JavaMail and Spring’s dependency. File : pom.xml <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 …

Read more

Spring PropertyPlaceholderConfigurer example

Often times, most Spring developers just put the entire deployment details (database details, log file path) in XML bean configuration file as following : <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-2.5.xsd"> <bean id="customerDAO" class="com.mkyong.customer.dao.impl.JdbcCustomerDAO"> <property name="dataSource" ref="dataSource" /> </bean> <bean id="customerSimpleDAO" class="com.mkyong.customer.dao.impl.SimpleJdbcCustomerDAO"> <property name="dataSource" ref="dataSource" /> </bean> <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/mkyongjava" …

Read more

Spring – Sending E-mail via Gmail SMTP server with MailSender

Spring comes with a useful ‘org.springframework.mail.javamail.JavaMailSenderImpl‘ class to simplify the e-mail sending process via JavaMail API. Here’s a Maven build project to use Spring’s ‘JavaMailSenderImpl‘ to send an email via Gmail SMTP server. 1. Project dependency Add the JavaMail and Spring’s dependency. File : pom.xml <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.mkyong.common</groupId> <artifactId>SpringExample</artifactId> <packaging>jar</packaging> <version>1.0-SNAPSHOT</version> …

Read more

Spring @PostConstruct and @PreDestroy example

In Spring, you can either implements InitializingBean and DisposableBean interface or specify the init-method and destroy-method in bean configuration file for the initialization and destruction callback function. In this article, we show you how to use annotation @PostConstruct and @PreDestroy to do the same thing. Note The @PostConstruct and @PreDestroy annotation are not belong to …

Read more

JavaMail API – Sending email via Gmail SMTP example

In this article, we will show you how to send an email via Gmail SMTP server. To send email in Java, we need JavaMail pom.xml <dependency> <groupId>com.sun.mail</groupId> <artifactId>javax.mail</artifactId> <version>1.6.2</version> </dependency> 1. Gmail SMTP via TLS SMTP = smtp.gmail.com Port = 587 SendEmailTLS.java package com.mkyong; import javax.mail.*; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import java.util.Properties; public class SendEmailTLS …

Read more

Spring Auto proxy creator example

In last Spring AOP examples – advice, pointcut and advisor, you have to manually create a proxy bean (ProxyFactoryBean) for each beans whose need AOP support. This is not an efficient way, for example, if you want all of your DAO classes in customer module to implement the AOP feature with SQL logging support (advise), …

Read more

Spring init-method and destroy-method example

In Spring, you can use init-method and destroy-method as attribute in bean configuration file for bean to perform certain actions upon initialization and destruction. Alternative to InitializingBean and DisposableBean interface. Example Here’s an example to show you how to use init-method and destroy-method. package com.mkyong.customer.services; public class CustomerService { String message; public String getMessage() { …

Read more

Spring InitializingBean and DisposableBean example

In Spring, InitializingBean and DisposableBean are two marker interfaces, a useful way for Spring to perform certain actions upon bean initialization and destruction. For bean implemented InitializingBean, it will run afterPropertiesSet() after all bean properties have been set. For bean implemented DisposableBean, it will run destroy() after Spring container is released the bean. Example Here’s …

Read more

Maven – How to download JavaMail API

JavaMail is now available in Maven Central repository. pom.xml <dependency> <groupId>com.sun.mail</groupId> <artifactId>javax.mail</artifactId> <version>1.6.2</version> </dependency> If you want to use the core JavaMail API to send email, you have to get the JavaMail library – mail.jar and activation.jar. Unfortunately, those libraries are not available in the Maven central repository, you have to download it from java.Net …

Read more

Spring bean scopes example

In Spring, bean scope is used to decide which type of bean instance should be return from Spring container back to the caller. 5 types of bean scopes supported : singleton – Return a single bean instance per Spring IoC container prototype – Return a new bean instance each time when requested request – Return …

Read more

Spring AOP Example – Pointcut , Advisor

In last Spring AOP advice examples, the entire methods of a class are intercepted automatically. But for most cases, you may just need a way to intercept only one or two methods, this is what ‘Pointcut’ come for. It allow you to intercept a method by it’s method name. In addition, a ‘Pointcut’ must be …

Read more

Spring AOP Example – Advice

Spring AOP + AspectJ Using AspectJ is more flexible and powerful, please refer to this tutorial – Using AspectJ annotation in Spring AOP. Spring AOP (Aspect-oriented programming) framework is used to modularize cross-cutting concerns in aspects. Put it simple, it’s just an interceptor to intercept some processes, for example, when a method is execute, Spring …

Read more

Spring Filter components in auto scanning

In this Spring auto component scanning tutorial, you learn about how to make Spring auto scan your components. In this article, we show you how to do component filter in auto scanning process. 1. Filter component – include See following example to use Spring “filtering” to scan and register components’ name which matched defined “regex”, …

Read more

Spring Auto scanning components

Normally you declare all the beans or components in XML bean configuration file, so that Spring container can detect and register your beans or components. Actually, Spring is able to auto scan, detect and instantiate your beans from pre-defined project package, no more tedious beans declaration in in XML file. Following is a simple Spring …

Read more

Maven + Spring + Hibernate + MySql Example

This example will use Maven to create a simple Java project structure, and demonstrate how to use Hibernate in Spring framework to do the data manipulation works(insert, select, update and delete) in MySQL database. Final project structure Your final project file structure should look exactly like following, if you get lost in the folder structure …

Read more

Spring Named Parameters examples in SimpleJdbcTemplate

In JdbcTemplate, SQL parameters are represented by a special placeholder “?” symbol and bind it by position. The problem is whenever the order of parameter is changed, you have to change the parameters bindings as well, it’s error prone and cumbersome to maintain it. To fix it, you can use “Named Parameter“, whereas SQL parameters …

Read more

Spring SimpleJdbcTemplate Querying examples

Here are few examples to show how to use SimpleJdbcTemplate query() methods to query or extract data from database. In JdbcTemplate query(), you need to manually cast the returned result to desire object type, and pass an Object array as parameters. In SimpleJdbcTemplate, it is more user friendly and simple. jdbctemplate vesus simplejdbctemplate Please compare …

Read more

Spring SimpleJdbcTemplate batchUpdate() example

In this tutorial, we show you how to use batchUpdate() in SimpleJdbcTemplate class. See batchUpdate() example in SimpleJdbcTemplate class. //insert batch example public void insertBatch(final List<Customer> customers){ String sql = "INSERT INTO CUSTOMER " + "(CUST_ID, NAME, AGE) VALUES (?, ?, ?)"; List<Object[]> parameters = new ArrayList<Object[]>(); for (Customer cust : customers) { parameters.add(new Object[] …

Read more

Spring JdbcTemplate Querying Examples

Here are a few examples to show you how to use Spring JdbcTemplate to query or extract data from database. Technologies used : Spring Boot 2.1.2.RELEASE Spring JDBC 5.1.4.RELEASE Maven 3 Java 8 In Short: jdbcTemplate.queryForObject for single row or value jdbcTemplate.query for multiple rows or list Note The article is updated from Spring core …

Read more

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

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 JdbcTemplate batchUpdate() Example

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 inject Date into bean property – CustomDateEditor

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 – How to access MessageSource in bean (MessageSourceAware)

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

ClassNotFoundException : org.springframework.web.context.ContextLoaderListener

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

Define custom @Required-style annotation in Spring

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

Spring Resource bundle with ResourceBundleMessageSource example

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