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

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

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

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

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

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

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

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