Spring – Read file from resources folder

In Spring, we can use ClassPathResource or ResourceLoader to get files from classpath easily. P.S Tested with Spring 5.1.4.RELEASE 1. src/main/resources/ For example, an image file in the src/main/resources/ folder 2. ClassPathResource import org.springframework.core.io.Resource; import org.springframework.core.io.ClassPathResource; import java.io.File; import java.io.InputStream; Resource resource = new ClassPathResource("android.png"); InputStream input = resource.getInputStream(); File file = resource.getFile(); 3. ResourceLoader …

Read more

JUnit + Spring integration example

In this tutorial, we will show you how to test the Spring DI components with JUnit frameworks. Technologies used : JUnit 4.12 Hamcrest 1.3 Spring 4.3.0.RELEASE Maven 1. Project Dependencies To integrate Spring with JUnit, you need spring-test.jar pom.xml <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> <exclusions> <exclusion> <groupId>org.hamcrest</groupId> <artifactId>hamcrest-core</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.hamcrest</groupId> <artifactId>hamcrest-library</artifactId> <version>1.3</version> …

Read more

Spring – Inject value into static variables

Spring doesn’t allow to inject value into static variables, for example: import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @Component public class GlobalValue { @Value("${mongodb.db}") public static String DATABASE; } If you print out the GlobalValue.DATABASE, a null will be displayed. GlobalValue.DATABASE = null Solution To fix it, create a “none static setter” to assign the injected value for …

Read more

Spring – Mixing XML and JavaConfig

Spring examples to show you how to mix both Spring XML and JavaConfig together. 1. Load JavaConfig From Spring XML A Spring MVC example, uses @Configuration to load everything, and you want integrate with web.xml SpringWebConfig.java package com.mkyong.form.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.springframework.web.servlet.view.InternalResourceViewResolver; import org.springframework.web.servlet.view.JstlView; @EnableWebMvc …

Read more

Spring embedded database examples

In this tutorial, we will show you a few examples to configure the embedded database engines like HSQL, H2 and Derby in Spring framework. Technologies used : Spring 4.1.6.RELEASE jUnit 4.1.2 Maven 3 Embedded databases tested : HSQLDB 2.3.2 H2 1.4.187 Derby 10.11.1.1 The embedded database concept is very helpful during the development phase, because …

Read more

Spring MethodInvokingFactoryBean Example

In Spring, you can use MethodInvokingFactoryBean to run a method, get the result and inject the result into another bean. This method invoker is very useful in XML configuration, but less use now in favor of annotation and Spring expression. 1. MethodInvokingFactoryBean 1.1 Example to get the current Java version. Spring XML Configuration <!– 1. …

Read more

Spring @Value – Import a list from properties file

In this tutorial, we will show you how to import a “List” from a properties file, via Spring EL @Value Tested with : Spring 4.0.6 JDK 1.7 Spring @Value and List In Spring @Value, you can use the split() method to inject the ‘List” in one line. config.properties server.name=hydra,zeus server.id=100,102,103 AppConfigTest.java package com.mkyong.analyzer.test; import java.util.List; …

Read more

Spring @PropertySource example

Spring default loads application.properties into the application’s environment, and we can use @PropertySource to load custom .properties files. file.properties file.path=/server1/file/path Application.java @Configuration @PropertySource("classpath:file.properties") public class Application { @Value("${file.path}") private String path; //… } Table of contents: 1. Project Structure 2. Properties Files 3. @PropertySource and @Value 4. Loads property files from multiple sources 5. Placeholder …

Read more

Spring @Value default value

This article shows how to provide a default value for the @Value annotation. In the below code, if the property.name doesn’t exist in the application properties or environment, defaultValue will be assigned to the propertyName field. SimpleComponent.java import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @Component public class SimpleComponent { @Value("${property.name:defaultValue}") private String propertyName; // getters, setters, etc } …

Read more

Spring – ${} is not working in @Value

A simple Spring @PropertySource example to read a properties file. db.properties db.driver=oracle.jdbc.driver.OracleDriver AppConfig.java @Configuration @PropertySource("classpath:db.properties") public class AppConfig { @Value("${db.driver}") private String driver; But the property placeholder ${} is unable to resolve in @Value, if print out the driver variable, it will display string ${db.driver} directly, instead of “oracle.jdbc.driver.OracleDriver”. Solution To resolve ${} in Spring …

Read more

Spring MVC Abstract Controller example

For self-reference, this article shows you how to create a Abstract class for Spring Controller, or a template method design pattern. 1. Abstract Controller In Abstract class, the @Controller annotation is optional, your implemented class will apply it. AbstractResultController.java package com.mkyong.web.controller; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; …

Read more

Spring Profiles example

Spring @Profile allow developers to register beans by condition. For example, register beans based on what operating system (Windows, *nix) your application is running, or load a database properties file based on the application running in development, test, staging or production environment. In this tutorial, we will show you a Spring @Profile application, which does …

Read more

Import Spring XML files into @Configuration

This is common to mix XML configuration into Spring @Configuration, because developers are used to the XML namespaces. In Spring, you can use @ImportResource to import Spring XML configuration files into @Configuration : AppConfig.java import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.ImportResource; @Configuration @ImportResource("classpath:/config/spring.xml") public class AppConfig { } Another example AppConfig.java import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.ImportResource; import org.springframework.context.annotation.Import; @Configuration …

Read more

Spring Caching and Ehcache example

In this tutorial, we will show you how to enable data caching in a Spring application, and integrate with the popular Ehcache framework. Tools used Ehcache 2.9 Spring 4.1.4.RELEASE Logback 1.0.13 Maven 3 / Gradle 2 JDK 1.7 Eclipse 4.4 Note Spring supports caching since version 3.1 Spring cache has been significantly improved since version …

Read more

How to autowire DataSource in JdbcDaoSupport

A Simple DAO class extends JdbcDaoSupport, but, unable to inject or @autowired a “dataSource”, the method setDataSource is final, can’t override. UserDetailsDaoImpl.java package com.mkyong.users.dao; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.support.JdbcDaoSupport; import org.springframework.stereotype.Repository; @Repository public class UserDetailsDaoImpl extends JdbcDaoSupport implements UserDetailsDao { //Error, cannot override the final method from JdbcDaoSupport @Autowired public void setDataSource(DataSource dataSource) { …

Read more

TestNG + Spring Integration Example

In this tutorial, we will show you how to test Spring’s components with TestNG. Tools used : TestNG 6.8.7 Spring 3.2.2.RELEASE Maven 3 Eclipse IDE 1. Project Dependencies To integrate Spring with TestNG, you need spring-test.jar, add the following : pom.xml <properties> <spring.version>3.2.2.RELEASE</spring.version> <testng.version>6.8.7</testng.version> </properties> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> …

Read more

Spring and Java Thread example

Here are 3 examples to show you how to do “threading” in Spring. See the code for self-explanatory. 1. Spring + Java Threads example Create a simple Java thread by extending Thread, and managed by Spring’s container via @Component. The bean scope must be “prototype“, so that each request will return a new instance, to …

Read more

Spring @Autowired into JSF custom validator

Here’s the scenario, create a custom JSF validator, injects a bean via Spring’s @Autowired. UsernameValidator.java – Custom JSF validator package com.mkyong.user; import javax.faces.application.FacesMessage; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.validator.FacesValidator; import javax.faces.validator.Validator; import javax.faces.validator.ValidatorException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import com.mkyong.user.bo.UserService; @Component @Scope("request") @FacesValidator("UsernameValidator") public class UsernameValidator implements Validator { @Autowired UserService userService; @Override public …

Read more

Spring 3 and JSR-330 @Inject and @Named example

Since Spring 3.0, Spring supports for the standard JSR 330: Dependency Injection for Java. In Spring 3 application, you can uses standard @Inject instead of Spring’s @Autowired to inject a bean. @Named instead of Spring’s @Component to declare a bean. Those JSR-330 standard annotations are scanned and retrieved the same way as Spring annotations, the …

Read more

How to inject null value in Spring

In Spring, you can uses this special <null /> tag to pass a “null” value into constructor argument or property. 1. Constructor Argument The wrong way to inject a null into constructor argument, a really common mistake, and nice try 🙂 <bean id="defaultMongoTypeMapper1" class="org.springframework.data.mongodb.core.convert.DefaultMongoTypeMapper"> <constructor-arg name="typeKey" value="null" /> </bean> Correct way. <bean id="defaultMongoTypeMapper" class="org.springframework.data.mongodb.core.convert.DefaultMongoTypeMapper"> <constructor-arg …

Read more

IncompatibleClassChangeError : JobDetailBean has interface org.quartz.JobDetail as super class

Developing Quartz 2.1.5 + Spring 3.1.2.RELEASE, hits following error messages : Caused by: java.lang.IncompatibleClassChangeError: class org.springframework.scheduling.quartz.JobDetailBean has interface org.quartz.JobDetail as super class at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClassCond(ClassLoader.java:631) at java.lang.ClassLoader.defineClass(ClassLoader.java:615) at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:141) at org.apache.catalina.loader.WebappClassLoader.findClassInternal(WebappClassLoader.java:2901) at org.apache.catalina.loader.WebappClassLoader.findClass(WebappClassLoader.java:1170) at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1678) at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1556) at org.springframework.util.ClassUtils.forName(ClassUtils.java:258) … 19 more Solution Quartz 2 APIs are changed a lot, and someone already …

Read more

java.lang.ClassNotFoundException: org.springframework.transaction.TransactionException

Developing Quartz with Spring 3, and hits following error message. Caused by: java.lang.NoClassDefFoundError: org/springframework/transaction/TransactionException at java.lang.Class.getDeclaredConstructors0(Native Method) at java.lang.Class.privateGetDeclaredConstructors(Class.java:2389) at java.lang.Class.getConstructor0(Class.java:2699) at java.lang.Class.getDeclaredConstructor(Class.java:1985) ….. Caused by: java.lang.ClassNotFoundException: org.springframework.transaction.TransactionException at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1711) at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1556) … 29 more Solution Doesn’t matter with Quartz, above error message show that you need Spring transaction dependency. To fix it, just include …

Read more

Jersey + Spring integration example

This tutorial show you how to integrate Jersey web application with Spring framework. Technologies used : Jersey 1.8 Spring 3.0.5.RELEASE Eclipse 3.6 Maven 3 1. Project Dependency Declares Jersey 1.8, Spring3 and “jersey-spring.jar” dependencies in Maven pom.xml file. Note In “jersey-spring.jar” version, it will download all the Spring 2.5.6 dependencies. To use Spring 3, you …

Read more

Spring request scope error : No thread-bound request found

Problem Developing web application with Spring, make a bean with scope of “request“. @Component @Scope("request") public class PaymentService { @Autowired UserBo userBo; //… But hit following error message? Caused by: java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally …

Read more

Spring AOP + AspectJ annotation example

In this tutorial, we show you how to integrate AspectJ annotation with Spring AOP framework. In simple, Spring AOP + AspectJ allow you to intercept method easily. Common AspectJ annotations : @Before – Run before the method execution @After – Run after the method returned a result @AfterReturning – Run after the method returned a …

Read more

Spring Autowiring @Qualifier example

In Spring, @Qualifier means, which bean is qualify to autowired on a field. See following scenario : Autowiring Example See below example, it will autowired a “person” bean into customer’s person property. package com.mkyong.common; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; public class Customer { @Autowired private Person person; //… } But, two similar beans “com.mkyong.common.Person” are declared …

Read more

Spring Autowiring by AutoDetect

In Spring, “Autowiring by AutoDetect“, means chooses “autowire by constructor” if default constructor (argument with any data type), otherwise uses “autowire by type“. See an example of Spring “auto wiring by autodetect”. Auto wiring the “kungfu” bean into “panda”, via constructor or type (base on the implementation of panda bean). <bean id="panda" class="com.mkyong.common.Panda" autowire="autodetect" /> …

Read more

Spring Autowiring by Constructor

In Spring, “Autowiring by Constructor” is actually autowiring by Type in constructor argument. It means, if data type of a bean is same as the data type of other bean constructor argument, auto wire it. See a full example of Spring auto wiring by constructor. 1. Beans Two beans, developer and language. package com.mkyong.common; public …

Read more

Spring DI via constructor

Uses Spring to dependency inject a bean via constructor. 1. IOutputGenerator An interface and implementation class of it. package com.mkyong.output; public interface IOutputGenerator { public void generateOutput(); } package com.mkyong.output.impl; import com.mkyong.output.IOutputGenerator; public class JsonOutputGenerator implements IOutputGenerator { public void generateOutput(){ System.out.println("This is Json Output Generator"); } } 2. Helper class A helper class, later …

Read more

Spring Autowiring by Type

In Spring, “Autowiring by Type” means, if data type of a bean is compatible with the data type of other bean property, auto wire it. For example, a “person” bean exposes a property with data type of “ability” class, Spring will find the bean with same data type of class “ability” and wire it automatically. …

Read more

Spring Autowiring by Name

In Spring, “Autowiring by Name” means, if the name of a bean is same as the name of other bean property, auto wire it. For example, if a “customer” bean exposes an “address” property, Spring will find the “address” bean in current container and wire it automatically. And if no matching found, just do nothing. …

Read more

Spring DI via setter method

A simple Spring example to show you how to dependency inject a bean via setter method, the most common used DI method. 1. IOutputGenerator An interface and implemntation class of it. package com.mkyong.output; public interface IOutputGenerator { public void generateOutput(); } package com.mkyong.output.impl; import com.mkyong.output.IOutputGenerator; public class CsvOutputGenerator implements IOutputGenerator { public void generateOutput() { …

Read more

BasicDataSource causing java.util.ConcurrentModificationException in WebSphere

Problem With Spring, declares data source as “org.apache.commons.dbcp.BasicDataSource“. When deployed to WebSphere, everything work perfectly. File : spring-datasource.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-2.5.xsd "> <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location"> <value>classpath:config/database/database.properties</value> </property> </bean> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${jdbc.driverClassName}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> </bean> …

Read more

JAX-WS + Spring integration example

Here’s a guide to show you how to integrate Spring with JAX-WS, as mention in this link : http://jax-ws-commons.java.net/spring/. Upon finishing this tutorial, you will create a simple HelloWorld web service (JAX-WS), and DI a bean into the web service via Spring. 1. Project Folder See the final project folder structure. 2. Project Dependencies Use …

Read more

Unable to locate Spring NamespaceHandler for XML schema namespace [http://jax-ws.dev.java.net/spring/servlet]

Problem Integrate Spring with JAX-WS, according to this link: http://jax-ws-commons.java.net/spring/ . When start the web application, get this exception : org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: Unable to locate Spring NamespaceHandler for XML schema namespace [http://jax-ws.dev.java.net/spring/servlet] Here’s the Spring + JAX-WS configuration file. <?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:ws="http://jax-ws.dev.java.net/spring/core" xmlns:wss="http://jax-ws.dev.java.net/spring/servlet" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://jax-ws.dev.java.net/spring/core http://jax-ws.dev.java.net/spring/core.xsd http://jax-ws.dev.java.net/spring/servlet http://jax-ws.dev.java.net/spring/servlet.xsd" > …

Read more

Spring + JAX-WS : ‘xxx’ is an interface, and JAXB can’t handle interfaces

Problem Integrate Spring + JAX-WS, see web service below : package com.mkyong.user.ws; //imports… @WebService() public class PGUserWS { //DI via Spring private UserBo userBo; public UserBo getUserBo() { return userBo; } public void setUserBo(UserBo userBo) { this.userBo = userBo; } @WebMethod(operationName = "addUser") public boolean addUser(@WebParam(name = "userId") String userId, @WebParam(name = "User") User user) …

Read more

Spring + jax-ws : ‘#xxx’ is not a valid value for ‘NCName’

Problem Here’s the Spring + JAX-WS configuration file … <?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:ws="http://jax-ws.dev.java.net/spring/core" xmlns:wss="http://jax-ws.dev.java.net/spring/servlet" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://jax-ws.dev.java.net/spring/core http://jax-ws.dev.java.net/spring/core.xsd http://jax-ws.dev.java.net/spring/servlet http://jax-ws.dev.java.net/spring/servlet.xsd" > <wss:binding url="/ws/OrderWs"> <wss:service> <ws:service bean="#orderWs"/> </wss:service> </wss:binding> <!– this bean implements web service methods –> <bean id="#orderWs" class="com.mkyong.order.ws.OrderWS"> <property name="orderBo" ref="OrderBo" /> </bean> </beans> During server start up, it hits following …

Read more

java.lang.ClassNotFoundException: org.apache.xbean.spring.context.v2.XBeanNamespaceHandler

Problem Developing jax-ws with Spring, using jdk1.6 + jaxws-spring-1.8.jar + Spring-2.5.6.jar. See following Spring XML configuration file : <?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:ws="http://jax-ws.dev.java.net/spring/core" xmlns:wss="http://jax-ws.dev.java.net/spring/servlet" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://jax-ws.dev.java.net/spring/core http://jax-ws.dev.java.net/spring/core.xsd http://jax-ws.dev.java.net/spring/servlet http://jax-ws.dev.java.net/spring/servlet.xsd" > <wss:binding url="/ws"> <wss:service> <ws:service bean="#UserWs"/> </wss:service> </wss:binding> <!– this bean implements web service methods –> <bean id="UserWs" class="com.mkyong.user.ws.UserWS"> <property name="UserBo" ref="com.mkyong.user.bo.UserBo" /> …

Read more