Spring Framework For All
Spring Framework For All
Spring is a framework for building Java applications. We can use Spring to build
any application in Java, for example, stand-alone, web, or Java Enterprise
Edition (JEE) applications).
Spring's philosophy is minimal impact.
Spring is lightweight in the sense that we have to make few, if any, changes to
your application code to gain the benefits of the Spring core.
JavaBeans
interfaces
Spring Features
Spring offers many modules, features and functions.
Spring Modules
Spring version 4.0.2.RELEASE comes with 20 modules, packaged into 20 JAR
files.
The following table describes these JAR files and their corresponding modules.
instrument Spring's instrumentation agent for Java Virtual Machine (JVM) bootstrapping.
instrument- Spring's instrumentation agent for JVM bootstrapping in the Tomcat server.
tomcat
messaging For message-based applications and adds support for STOMP messages.
orm Spring's standard JDBC feature set with support for popular ORM tools including Hibernate,
JDO, JPA.
web-portlet For using Spring MVC in developing portlets for deployment to a portal server environment.
mvn eclipse:eclipse
Spring dependency
Add Spring dependency in Maven's pom.xml file.
Full 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.apac
he.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.java2s.common</groupId>
<artifactId>Java2sExamples</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>Java2sExamples</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!-- Spring framework -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring</artifactId>
<version>2.5.6</version>
</dependency>
</dependencies>
</project>
Spring bean
Spring's bean is just a normal Java class. It has fields with getter and setter.
Later we will declare in Spring bean configuration file.
Add the following code to "src/main/java/com/java2s/common/HelloWorld.java".
package com.java2s.common;
public class HelloWorld {
private String name;
<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-3.0.xsd">
</beans>
package com.java2s.common;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
mvn compile
Setup Eclipse
The following screenshots show how to setup eclipse ide to work with Spring.
Import the pom.xml to Eclipse
Use the following command to convert Maven style project to Eclipse's style
project, and import the project into Eclipse IDE.
mvn eclipse:eclipse
package com.java2s.common;
<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-3.0.xsd">
</beans>
package com.java2s.common;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
The following sections show how to use the annotation to mark dependencies
for Spring
Java Bean
Create a a simple bean as follows.
package com.java2s.common;
package com.java2s.common;
The following code shows how to use use @Configuration to tell Spring that this
is the core Spring configuration file, and define bean via @Bean.
package com.java2s.common;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AppConfig {
@Bean(name="helloBean")
public HelloWorld helloWorld() {
return new HelloWorldImpl();
}
}
Main method
In order to load the our JavaConfig class use
AnnotationConfigApplicationContext.
package com.java2s.common;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext
;
}
}
Output
Download Java2s_Spring_JavaConfig.zip
Spring 3 JavaConfig @Import example
Two simple Spring beans.
File : Customer.java
package com.java2s.common;
File : Employee.java
package com.java2s.common;
public class Employee {
public void printMsg(String msg) {
System.out.println("Employee : " + msg);
}
}
package com.java2s.common;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class CustomerConfig {
@Bean(name="customer")
public Customer customer(){
return new Customer();
}
}
File : EmployeeConfig.java
package com.java2s.common;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class EmployeeConfig {
@Bean(name="employee")
public Employee employee(){
return new Employee();
}
}
package com.java2s.common;
org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
@Configuration
@Import({ CustomerConfig.class, EmployeeConfig.class })
public class AppConfig {
}
package com.java2s.common;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext
;
import com.java2s.config.AppConfig;
public class App {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(
AppConfig.class);
Customer customer = (Customer) context.getBean("customer");
customer.printMsg("Hello 1");
Employee employee = (Employee) context.getBean("employee");
employee.printMsg("Hello 2");
}
}
Output
In the following we will see how Spring would help us to achieve loosely
coupled code.
Project Code
We would create a project which has several classes. Th project would output
data in different format. We can choose to output the data in CSV format or
JSON format.
First we will create a Java interface for print.
package com.java2s.output;
public interface Printer
{
public void print();
}
After that we would create CSV printer which will output data in CSV format.
The CSV printer implements the Printer interface.
package com.java2s.output.impl;
import com.java2s.output.Printer;
public class CSVPrinter implements Printer
{
public void print(){
System.out.println("Csv Output Printer");
}
}
Then it is time to create JSON printer which will output message in JSON
format. The JSON printer also implements the Printer interface.
package com.java2s.output.impl;
import com.java2s.output.Printer;
public class JSONPrinter implements Printer
{
public void print(){
System.out.println("Json Output Printer");
}
}
Couple Code
We have several ways to use the CSVPrinter or JSONPrinter. First we can call
it directly.
package com.java2s.common;
import com.java2s.output.Printer;
import com.java2s.output.impl.CSVPrinter;
public class App
{
public static void main( String[] args )
{
Printer output = new CSVPrinter();
output.print();
}
}
It is easy to create CSVPrinter in this way. But we will have to change the
source code if we want to switch to JSONPrinter we will have to change the
source code and recompile.
For the code above it is easy to change since it has two lines of code. Suppose
we have thousands of thousands of code and the CSVPrinter had been
declared hundreds of time.
Spring Way
By using Spring Dependency Injection (DI) we can declare Java Beans in the
Spring configuration xml file. Then wire the Java Beans in the xml file. In this
way Spring can make our printer loosely coupled to the different Printer
implementations.
We change the Helper class to accept the Printer.
package com.java2s.output;
import com.java2s.output.Printer;
public class OutputHelper
{
Printer outputGenerator;
public void print(){
outputGenerator.print();
}
public void setOutputGenerator(Printer outputGenerator){
this.outputGenerator = outputGenerator;
}
}
Then we have to create a Spring bean configuration file and declare all your
Java object dependencies here.
<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="OutputHelper" class="com.java2s.output.OutputHelper">
<property name="outputGenerator" ref="csvPrinter" />
</bean>
<bean id="csvPrinter" class="com.java2s.output.impl.CSVPrinter" />
<bean id="jsonPrinter" class="com.java2s.output.impl.JSONPrinter" />
</beans>
package com.java2s.common;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.java2s.output.OutputHelper;
public class App
{
public static void main( String[] args )
{
ApplicationContext context =
new ClassPathXmlApplicationContext(new String[] {"Spring-Common.xml"});
OutputHelper output = (OutputHelper)context.getBean("OutputHelper");
output.print();
}
}
To switch Printer, we just need to change the Spring XML file for a different
Printer. When Printer changed, we need to modify the Spring XML file only.
Spring Setter injection is the most popular and simple dependency injection
method, it will injects the dependency via a setter method.
In Setter Dependency Injection , the IoC container injects a Java Bean's
dependencies via JavaBean-style setter methods.
A Java Bean's setters expose the dependencies the IoC container can manage.
In practice, Setter Injection is the most widely used injection mechanism, and it
is one of the simplest IoC mechanisms to implement.
Example
Suppose we have the following interface and Java beans defined.
package com.java2s.common;
public interface Printer
{
public void print();
}
After that we would create CSV printer which will output data in CSV format.
The CSV printer implements the Printer interface.
package com.java2s.common;
public class CSVPrinter implements Printer
{
public void print(){
System.out.println("Csv Output Printer");
}
}
Then it is time to create JSON printer which will output message in JSON
format. The JSON printer also implements the Printer interface.
package com.java2s.common;
public class JSONPrinter implements Printer
{
public void print(){
System.out.println("Json Output Printer");
}
}
By using Spring Dependency Injection (DI) we can declare Java Beans in the
Spring configuration xml file. Then wire the Java Beans in the xml file. In this
way Spring can make our printer loosely coupled to the different Printer
implementations.
We change the Helper class to accept the Printer.
package com.java2s.common;
public class OutputHelper
{
Printer outputGenerator;
public void print(){
outputGenerator.print();
}
public void setOutputGenerator(Printer outputGenerator){
this.outputGenerator = outputGenerator;
}
}
XML Configuration
Then we have to create a Spring bean configuration file and declare all your
Java object dependencies here.
<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="outputHelper" class="com.java2s.common.OutputHelper">
<property name="outputGenerator" ref="csvPrinter" />
</bean>
<bean id="csvPrinter" class="com.java2s.common.CSVPrinter" />
<bean id="jsonPrinter" class="com.java2s.common.JSONPrinter" />
</beans>
The following two bean tags declared two Java Beans in Spring configuration
xml file.
After the declaration we can use the id value to reference the Java Beans.
The following xml bean tag declared the OutputHelper and inject the
dependency via setter injection by using property tag.
package com.java2s.common;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class App {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext(
"SpringBeans.xml");
OutputHelper output = (OutputHelper)context.getBean("outputHelper");
output.print();
}
}
Output
Example
Suppose we have the following interface and Java beans defined.
package com.java2s.common;
public interface Printer
{
public void print();
}
After that we would create CSV printer which will output data in CSV format.
The CSV printer implements the Printer interface.
package com.java2s.common;
public class CSVPrinter implements Printer
{
public void print(){
System.out.println("Csv Output Printer");
}
}
Then it is time to create JSON printer which will output message in JSON
format. The JSON printer also implements the Printer interface.
package com.java2s.common;
public class JSONPrinter implements Printer
{
public void print(){
System.out.println("Json Output Printer");
}
}
package com.java2s.common;
public class OutputHelper
{
Printer outputGenerator;
public OutputHelper(){
}
public OutputHelper(Printer p){
this.outputGenerator = p;
}
public void print(){
outputGenerator.print();
}
The following Spring bean configuration file declares the beans and set the
dependency via constructor injection by using constructor-arg tag.
<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="outputHelper" class="com.java2s.common.OutputHelper">
<constructor-arg>
<bean class="com.java2s.common.CSVPrinter" />
</constructor-arg>
</bean>
<bean id="csvPrinter" class="com.java2s.common.CSVPrinter" />
<bean id="jsonPrinter" class="com.java2s.common.JSONPrinter" />
</beans>
package com.java2s.common;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class App {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext(
"SpringBeans.xml");
OutputHelper output = (OutputHelper)context.getBean("outputHelper");
output.print();
}
}
Output
package com.java2s.common;
public class Employee
{
private String name;
private String address;
private int age;
public Employee(String name, String address, int age) {
this.name = name;
this.address = address;
this.age = age;
}
public Employee(String name, int age, String address) {
this.name = name;
this.age = age;
this.address = address;
}
public String toString(){
return " name : " +name + " address : " + address + " age : " + age;
}
}
<myPreCode>
<beans ...
<bean id="myEmployee" class="com.java2s.common.Employee">
<constructor-arg>
<value>java2s</value>
</constructor-arg>
<constructor-arg>
<value>1000</value>
</constructor-arg>
<constructor-arg>
<value>28</value>
</constructor-arg>
</bean>
</beans>
package com.java2s.common;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class App
{
public static void main( String[] args )
{
ApplicationContext context =
new ClassPathXmlApplicationContext(new String[] {"Spring-Employee.xml"})
;
Employee cust = (Employee)context.getBean("myEmployee");
System.out.println(cust);
}
}
Output
From the result string we can see that the second constructor is called rather than the
first constructor.
Spring converts the argument '1000' to int, and then calls take the second constructor,
even we passed in the value as a String type.
If Spring cannot find the proper constructor to use, it will prompt following error
message
In order to match the parameter type in the constructor, we can specify the data type for
constructor, via type attribute in the constructor-arg tag.
<beans ...
<bean id="myEmployee" class="com.java2s.common.Employee">
<constructor-arg type="java.lang.String">
<value>java2s</value>
</constructor-arg>
<constructor-arg type="java.lang.String">
<value>1000</value>
</constructor-arg>
<constructor-arg type="int">
<value>28</value>
</constructor-arg>
</bean>
</beans>
Run it again.
In a big project we may have several Spring configuration files. One Java bean
is defined in one Spring xml configuration file can be referenced in another
configuration file via ref tag.
The ref tag has the following syntax.
<ref bean="someBean"/>
In the following Spring-Output.xml file we created two Java Beans and gave
them id.
<beans ...
<bean id="CSVPrinter" class="com.java2s.output.impl.CSVPrinter" />
<bean id="JSONPrinter" class="com.java2s.output.impl.JSONPrinter" />
</beans>
<beans ...
<bean id="PrinterHelper" class="com.java2s.output.PrinterHelper">
<property name="outputGenerator" >
<ref bean="CSVPrinter"/>
</property>
</bean>
</beans>
<ref local="someBean"/>
In the following xml code, the bean "PrinterHelper" declared in 'Spring-
Common.xml' can access "CSVPrinter" or "JSONPrinter" which are defined in
the same file with ref local.
<beans ...
<bean id="PrinterHelper" class="com.java2s.output.PrinterHelper">
<property name="outputGenerator" >
<ref local="CSVPrinter"/>
</property>
</bean>
<bean id="CSVPrinter" class="com.java2s.output.impl.CSVPrinter" />
<bean id="JSONPrinter" class="com.java2s.output.impl.JSONPrinter" />
</beans>
By using ref local we increase the readability of the xml configuration file.
We can fill data to a Java Bean defined in the Spring configuration xml in
several ways.
The following sections show to inject value to the name and type properties
defined in the MyClass.
package com.java2s.common
public class MyClass {
private String name;
private String type;
public String getName() {
return name;/*from w w w . j ava 2 s . c om*/
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
<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="myClass" class="com.java2s.common.MyClass">
<property name="name">
<value>java2s</value>
</property>
<property name="type">
<value>txt</value>
</property>
</bean>
</beans>
After loading the myClass from Spring configuration xml file the name and type
properties are set to java2s and txt respectively.
<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="MyClass" class="com.java2s.common.MyClass">
<property name="name" value="java2s" />
<property name="type" value="txt" />
</bean>
</beans>
"p" schema
We can even fill the properties when declaring the Java Bean in the bean tag.
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="MyClass" class="com.java2s.common.MyClass"
p:name="java2s" p:type="txt" />
</beans>
In a large project, we may have more than one Spring's bean configuration files.
Put every single bean definition in a single file is hard to maintain. And they
may be stored in different folder structures.
For example, we may have a Spring-Common.xml in common folder, a Spring-
Connection.xml in connection folder, and a Spring-ModuleA.xml in ModuleA
folder.
Then we can use the following code to load multiple Spring bean configuration
files.
ApplicationContext context =
new ClassPathXmlApplicationContext(new String[] {"Spring-Common.xml",
"Spring-Connection.xml","Spring-ModuleA.xml"});
<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">
<import resource="common/Spring-Common.xml"/>
<import resource="connection/Spring-Connection.xml"/>
<import resource="moduleA/Spring-ModuleA.xml"/>
</beans>
project-classpath/Spring-All-Module.xml
ApplicationContext context =
new ClassPathXmlApplicationContext("Spring-All-Module.xml");
package com.java2s.common;
public class Customer
{
private Person person;
public Customer() {
}
public Customer(Person person) {
this.person = person;
}
public void setPerson(Person person) {
this.person = person;
}
@Override
public String toString() {
return "Customer [person=" + person + "]";
}
}
package com.java2s.common;
public class Person
{
private String name;
private String address;
private int age;
public String getName() {
return name;
}
@Override
public String toString() {
return "Person [address=" + address + ",age=" + age + ", name=" + name + "]"
;
}
}
Reference Inner Java Beans
One way to inject Person Java bean to Customer bean is to use ref attribute as
follows.
<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="CustomerBean" class="com.java2s.common.Customer">
<property name="person" ref="PersonBean" />
</bean>
<bean id="PersonBean" class="com.java2s.common.Person">
<property name="name" value="java2s" />
<property name="address" value="address1" />
<property name="age" value="28" />
</bean>
</beans>
The Person bean is defined in the same level with Customer bean and we use
ref attribute to reference the Person bean.
If the Person bean is only used in Customer bean we can nest the definition of
Person bean inside the Customer bean.
<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="CustomerBean" class="com.java2s.common.Customer">
<property name="person">
<bean class="com.java2s.common.Person">
<property name="name" value="java2s" />
<property name="address" value="address1" />
<property name="age" value="28" />
</bean>
</property>
</bean>
</beans>
The following xml code shows how to use inner bean for constructor injection.
<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="CustomerBean" class="com.java2s.common.Customer">
<constructor-arg>
<bean class="com.java2s.common.Person">
<property name="name" value="java2s" />
<property name="address" value="address1" />
<property name="age" value="28" />
</bean>
</constructor-arg>
</bean>
</beans>
package com.java2s.common;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class App
{
public static void main( String[] args )
{
ApplicationContext context =
new ClassPathXmlApplicationContext(new String[] {"SpringBeans.xml"});
Customer cust = (Customer)context.getBean("CustomerBean");
System.out.println(cust);
}
}
Output
When defining Java bean in Spring xml configuration or using the Spring
annotation we can mark a Java bean as singleton or prototype.
If a Java bean is marked as singleton, each time we call to get the bean we get
the same instance.
If a Java bean is marked as prototype, each time we will get a new instance.
Java Bean
The following code defines a Java bean with a String type property.
package com.java2s.common;
public class MyService
{
String message;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
Singleton
If no bean scope is specified in bean configuration file, default to singleton.
<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="customerService"
class="com.java2s.common.MyService" />
</beans>
package com.java2s.common;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class App
{
public static void main( String[] args )
{
ApplicationContext context =
new ClassPathXmlApplicationContext(new String[] {"SpringBeans.x
ml"});
MyService customerA = (MyService)context.getBean("customerService");
customerA.setMessage("Message by customerA");
System.out.println("Message : " + customerA.getMessage());
//retrieve it again
MyService custB = (MyService)context.getBean("customerService");
System.out.println("Message : " + custB.getMessage());
}
}
Output
The code above get MyService twice from the ApplicationContext. And it sets
a String value for the message after the first call.
From the output we can see that both getMessage() call return the same
message, which means the ApplicationContext uses one copy of the MyService.
If a bean is a singleton scope in Spring IoC container, getBean() will always
return the same instance.
Prototype
To get a new 'customerService' bean instance every time we call getBean(),
use prototype scope.
<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="customerService" class="com.java2s.common.MyService"
scope="prototype"/>
</beans>
Run it again
package com.java2s.common;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
@Service
@Scope("prototype")
public class MyService {
String message;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<context:component-scan base-package="com.java2s.common" />
</beans>
package com.java2s.common;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class App
{
public static void main( String[] args )
{
ApplicationContext context =
new ClassPathXmlApplicationContext(new String[] {"SpringBeans.x
ml"});
MyService customerA = (MyService)context.getBean("myService");
customerA.setMessage("Message by customerA");
System.out.println("Message : " + customerA.getMessage());
//retrieve it again
MyService custB = (MyService)context.getBean("myService");
System.out.println("Message : " + custB.getMessage());
}
}
Run it again
We can fill value or a list of values to a Java bean defined in Spring xml
configuration file.
The following sections shows how to fill data to List.
Java Bean
In order to show how to use xml configuration file to fill collection properties, we
defined a Customer object with four collection properties.
package com.java2s.common;
import java.util.ArrayList;
import java.util.List;
public class Customer
{
private List<Object> lists = new ArrayList<Object>();
public String toString(){
return lists.toString();
}
public List<Object> getLists() {
return lists;
}
public void setLists(List<Object> lists) {
this.lists = lists;
}
}
package com.java2s.common;
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + ", address=" + address
+ "]";
}
List
The following code shows how to fill data to a java.util.List typed property.
The code fills in three values. The first one is hard-coded value 1. The second
one is a bean reference. We have to define PersonBean somewhere in order to
use it here. The third one is a bean definition with property-setting.
...
<property name="lists">
<list>
<value>1</value>
<ref bean="PersonBean" />
<bean class="com.java2s.common.Person">
<property name="name" value="java2sList" />
<property name="address" value="address" />
<property name="age" value="28" />
</bean>
</list>
</property>
...
Example
Full Spring's bean configuration file.
<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="CustomerBean" class="com.java2s.common.Customer">
<!-- java.util.List -->
<property name="lists">
<list>
<value>1</value>
<ref bean="PersonBean" />
<bean class="com.java2s.common.Person">
<property name="name" value="java2sList" />
<property name="address" value="address" />
<property name="age" value="28" />
</bean>
</list>
</property>
</bean>
<bean id="PersonBean" class="com.java2s.common.Person">
<property name="name" value="java2s1" />
<property name="address" value="address 1" />
<property name="age" value="28" />
</bean>
</beans>
package com.java2s.common;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class App
{
public static void main( String[] args )
{
ApplicationContext context = new ClassPathXmlApplicationContext("SpringBea
ns.xml");
Customer cust = (Customer)context.getBean("CustomerBean");
System.out.println(cust);
}
}
Output
ListFactoryBean
ListFactoryBean class can create a concrete List collection class with ArrayList
or LinkedList in Spring's bean configuration file. Then we can inject the created
list object to our Java bean.
Here is the Java bean class.
package com.java2s.common;
import java.util.ArrayList;
import java.util.List;
public class Customer
{
private List<Object> lists = new ArrayList<Object>();
public String toString(){
return lists.toString();
}
public List<Object> getLists() {
return lists;
}
public void setLists(List<Object> lists) {
this.lists = lists;
}
}
<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">
//from w w w. ja va 2 s.com
<bean id="CustomerBean" class="com.java2s.common.Customer">
<property name="lists">
<bean class="org.springframework.beans.factory.config.ListFactoryBean">
<property name="targetListClass">
<value>java.util.ArrayList</value>
</property>
<property name="sourceList">
<list>
<value>1</value>
<value>2</value>
<value>3</value>
</list>
</property>
</bean>
</property>
</bean>
</beans>
util schema
We also can use util schema and <util:list> to fill data to a list.
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-2.5.xsd">
<bean id="CustomerBean" class="com.java2s.common.Customer">
<property name="lists">
<util:list list-class="java.util.ArrayList">
<value>1</value>
<value>2</value>
<value>3</value>
</util:list>
</property>
</bean>
</beans>
package com.java2s.common;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
}
}
We can fill value or a list of values to a Java bean defined in Spring xml
configuration file.
The following sections show how to fill data to Set.
Java Bean
In order to show how to use xml configuration file to fill collection properties, we
defined a Customer object with four collection properties.
package com.java2s.common;
import java.util.HashSet;
import java.util.Set;
package com.java2s.common;
Set
The following code shows how to fill data to a java.util.Set typed property.
The code fills in three values. The first one is hard-coded value 1. The second
one is a bean reference. We have to define PersonBean somewhere in order to
use it here. The third one is a bean definition with property-setting.
...
<property name="sets">
<set>
<value>1</value>
<ref bean="PersonBean" />
<bean class="com.java2s.common.Person">
<property name="name" value="java2sSet" />
<property name="address" value="address" />
<property name="age" value="28" />
</bean>
</set>
</property>
...
Example
Full Spring's bean configuration file.
<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="CustomerBean" class="com.java2s.common.Customer">
<!-- java.util.Set -->
<property name="sets">
<set>
<value>1</value>
<ref bean="PersonBean" />
<bean class="com.java2s.common.Person">
<property name="name" value="java2sSet" />
<property name="address" value="address" />
<property name="age" value="28" />
</bean>
</set>
</property>
</bean>
<bean id="PersonBean" class="com.java2s.common.Person">
<property name="name" value="java2s1" />
<property name="address" value="address 1" />
<property name="age" value="28" />
</bean>
</beans>
package com.java2s.common;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
Output
Customer [
sets=[
1,
Person [address=address 1, age=28, name=java2s1],
Person [address=address, age=28, name=java2sSet]]
]
SetFactoryBean
SetFactoryBean class can create a concrete Set collection HashSet or TreeSet
in Spring's bean configuration file.
The following code shows how to use SetFactoryBean.
Here is the Java bean class.
package com.java2s.common;
//from w w w. j av a 2 s. co m
import java.util.HashSet;
import java.util.Set;
<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="CustomerBean" class="com.java2s.common.Customer">
<property name="sets">
<bean class="org.springframework.beans.factory.config.SetFactoryBean">
<property name="targetSetClass">
<value>java.util.HashSet</value>
</property>
<property name="sourceSet">
<list>
<value>1</value>
<value>2</value>
<value>3</value>
</list>
</property>
</bean>
</property>
</bean>
</beans>
util schema
We also can use util schema and <util:set> to fill data to java.util.Set.
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-2.5.xsd">
<bean id="CustomerBean" class="com.java2s.common.Customer">
<property name="sets">
<util:set set-class="java.util.HashSet">
<value>1</value>
<value>2</value>
<value>3</value>
</util:set>
</property>
</bean>
</beans>
package com.java2s.common;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class App
{
public static void main( String[] args )
{
ApplicationContext context = new ClassPathXmlApplicationContext("SpringBea
ns.xml");
}
}
We can fill value or a list of values to a Java bean defined in Spring xml
configuration file.
The following sections shows how to fill data to Map.
Java Bean
In order to show how to use xml configuration file to fill collection properties, we
defined a Customer object with four collection properties.
package com.java2s.common;
import java.util.HashMap;
import java.util.Map;
package com.java2s.common;
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + ", address=" + address
+ "]";
}
}
Map
The following code shows how to fill data to a java.util.Set typed property.
The code fills in three values. The first one is hard-coded value 1. The second
one is a bean reference. We have to define PersonBean somewhere in order to
use it here. The third one is a bean definition with property-setting. When filling
data for java.util.Map we have to provide key and value pair.
...
<property name="maps">
<map>
<entry key="Key 1" value="1" />
<entry key="Key 2" value-ref="PersonBean" />
<entry key="Key 3">
<bean class="com.java2s.common.Person">
<property name="name" value="java2sMap" />
<property name="address" value="address" />
<property name="age" value="28" />
</bean>
</entry>
</map>
</property>
...
Example
Full Spring's bean configuration file.
<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="CustomerBean" class="com.java2s.common.Customer">
<!-- java.util.Map -->
<property name="maps">
<map>
<entry key="Key 1" value="1" />
<entry key="Key 2" value-ref="PersonBean" />
<entry key="Key 3">
<bean class="com.java2s.common.Person">
<property name="name" value="java2sMap" />
<property name="address" value="address" />
<property name="age" value="28" />
</bean>
</entry>
</map>
</property>
</bean>
<bean id="PersonBean" class="com.java2s.common.Person">
<property name="name" value="java2s1" />
<property name="address" value="address 1" />
<property name="age" value="28" />
</bean>
</beans>
package com.java2s.common;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class App
{
public static void main( String[] args )
{
ApplicationContext context = new ClassPathXmlApplicationContext("SpringBea
ns.xml");
Customer cust = (Customer)context.getBean("CustomerBean");
System.out.println(cust);
}
}
Output
MapFactoryBean
MapFactoryBean class can create a Map collection class HashMap or TreeMap
in Spring's bean configuration file.
The following code shows how to create a HashMap, fill data and then inject it
into a bean property.
Here is the Java bean class.
package com.java2s.common;
//from w w w . ja va2 s . c om
import java.util.HashMap;
import java.util.Map;
<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="CustomerBean" class="com.java2s.common.Customer">
<property name="maps">
<bean class="org.springframework.beans.factory.config.MapFactoryBean">
<property name="targetMapClass">
<value>java.util.HashMap</value>
</property>
<property name="sourceMap">
<map>
<entry key="Key1" value="1" />
<entry key="Key2" value="2" />
<entry key="Key3" value="3" />
</map>
</property>
</bean>
</property>
</bean>
</beans>
util schema
We also can use util schema and <util:map> to fill data to java.util.Map.
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-2.5.xsd">
<bean id="CustomerBean" class="com.java2s.common.Customer">
<property name="maps">
<util:map map-class="java.util.HashMap">
<entry key="Key1" value="1" />
<entry key="Key2" value="2" />
<entry key="Key3" value="3" />
</util:map>
</property>
</bean>
</beans>
package com.java2s.common;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class App
{
public static void main( String[] args )
{
ApplicationContext context = new ClassPathXmlApplicationContext("SpringBea
ns.xml");
Customer cust = (Customer)context.getBean("CustomerBean");
System.out.println(cust);
}
}
We can fill value or a list of values to a Java bean defined in Spring xml
configuration file.
The following sections shows how to fill data to java.util.Properties.
Java Bean
In order to show how to use xml configuration file to fill collection properties, we
defined a Customer object with four collection properties.
package com.java2s.common;
import java.util.Properties;
public class Customer
{
private Properties pros = new Properties();
package com.java2s.common;
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + ", address=" + address
+ "]";
}
Properties
java.util.Properties is a key-value pair structrue and we can use the following
syntax to fill data for it.
...
<property name="pros">
<props>
<prop key="admin">user a</prop>
<prop key="support">user b</prop>
</props>
</property>
...
Example
Full Spring's bean configuration file.
<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="CustomerBean" class="com.java2s.common.Customer">
<!-- java.util.Properties -->
<property name="pros">
<props>
<prop key="admin">user a</prop>
<prop key="support">user b</prop>
</props>
</property>
</bean>
<bean id="PersonBean" class="com.java2s.common.Person">
<property name="name" value="java2s1" />
<property name="address" value="address 1" />
<property name="age" value="28" />
</bean>
</beans>
package com.java2s.common;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class App
{
public static void main( String[] args )
{
ApplicationContext context = new ClassPathXmlApplicationContext("SpringBea
ns.xml");
Customer cust = (Customer)context.getBean("CustomerBean");
System.out.println(cust);
}
}
Output
Customer [
pros={admin=user a, support=user b},
The following sections shows how to fill data to java.util.Date type value.
Java Bean
Here is the Java bean class we are going to use.
package com.java2s.common;
import java.util.Date;
//from w w w . j a v a2 s . c om
public class Customer {
Date date;
@Override
public String toString() {
return "Customer [date=" + date + "]";
}
Factory bean
The following code shows how to parse a String value to a Date value and then
set to Java bean.
It create a Java bean from java.text.SimpleDateFormat and parse in the
format as yyyy-MM-dd. Then it use the dateFormat bean as factory-bean and
use the parse method as the factory-method.
In the constructor-arg tag it sets the value to the date properties.
<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="dateFormat" class="java.text.SimpleDateFormat">
<constructor-arg value="yyyy-MM-dd" />
</bean>
<bean id="customer" class="com.java2s.common.Customer">
<property name="date">
<bean factory-bean="dateFormat" factory-method="parse">
<constructor-arg value="2010-01-31" />
</bean>
</property>
</bean>
</beans>
Download Java2s_Spring_DateFactory.zip
CustomDateEditor
In the second method to fill date value, we use the CustomDateEditor class.
In the bean xml configuration file it declares a CustomDateEditor class to
convert String into java.util.Date.
<bean id="dateEditor"
class="org.springframework.beans.propertyeditors.CustomDateEditor">
<constructor-arg>
<bean class="java.text.SimpleDateFormat">
<constructor-arg value="yyyy-MM-dd" />
</bean>
</constructor-arg>
<constructor-arg value="true" />
</bean>
<bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
<property name="customEditors">
<map>
<entry key="java.util.Date">
<ref local="dateEditor" />
</entry>
</map>
</property>
</bean>
<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="dateEditor"
class="org.springframework.beans.propertyeditors.CustomDateEditor">
<constructor-arg>
<bean class="java.text.SimpleDateFormat">
<constructor-arg value="yyyy-MM-dd" />
</bean>
</constructor-arg>
<constructor-arg value="true" />
</bean>
<bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
<property name="customEditors">
<map>
<entry key="java.util.Date">
<ref local="dateEditor" />
</entry>
</map>
</property>
</bean>
<bean id="customer" class="com.java2s.common.Customer">
<property name="date" value="2010-02-31" />
</bean>
</beans>
package com.java2s.common;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class App {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext(
"SpringBeans.xml");
Customer cust = (Customer) context.getBean("customer");
System.out.println(cust);
}
}
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/java2sjava
jdbc.username=root
jdbc.password=password
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfig
urer">
<property name="location">
<value>database.properties</value>
</property>
</bean>
<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.PropertyPlaceholderConfi
gurer">
<property name="location">
<value>database.properties</value>
</property>
</bean>
<bean id="customerDAO" class="com.java2s.customer.dao.impl.JdbcCustomerDAO">
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="customerSimpleDAO"
class="com.java2s.customer.dao.impl.SimpleJdbcCustomerDAO">
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<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>
</beans>
Spring supports bean configuration inheritance. We can define a bean and then
further configure it to create new bean.
By using the bean inheritance we can share common values, properties or
configurations.
A child bean inherits its parent bean configurations, properties and attributes.
In addition, the child beans can override the inherited value.
Java Bean
package com.java2s.common;
public class Customer {
private int type;
private String action;
private String Country;
public int getType() {
return type;
}//from w ww.ja v a 2 s.co m
public void setType(int type) {
this.type = type;
}
public String getAction() {
return action;
}
public void setAction(String action) {
this.action = action;
}
public String getCountry() {
return Country;
}
public void setCountry(String country) {
Country = country;
}
@Override
public String toString() {
return "Customer [type=" + type + ", action=" + action + ", Country="
+ Country + "]";
}
}
Bean configuration file
Here is the Bean configuration file
<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="generalCustomer" class="com.java2s.common.Customer">
<property name="country" value="USA" />
</bean>
<bean id="specialCustomer" parent="generalCustomer">
<property name="action" value="backup" />
<property name="type" value="1" />
</bean>
</beans>
package com.java2s.common;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class App
{
public static void main( String[] args )
{
ApplicationContext context =
new ClassPathXmlApplicationContext("SpringBeans.xml");
Customer cust = (Customer)context.getBean("specialCustomer");
System.out.println(cust);
}
}
Download Java2s_Spring_Bean_Inheritance.zip
abstract bean
In above example, we can still instantiate the 'generalCustomer' bean as
follows.
To make this base bean as a template and not allow Java code to instantiate it,
add an 'abstract' attribute in the <bean> element.
<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="generalCustomer" class="com.java2s.common.Customer" abstract="true">
<property name="country" value="USA" />
</bean>
<bean id="specialCustomer" parent="generalCustomer">
<property name="action" value="backup" />
<property name="type" value="1" />
</bean>
</beans>
Bean Template
A parent bean doesn't need class attribute, it just need common properties for
sharing.
Here's is an example
<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="generalCustomer" abstract="true">
<property name="country" value="USA" />
</bean>
<bean id="specialCustomer" parent="generalCustomer"
class="com.java2s.common.Customer">
<property name="action" value="backup" />
<property name="type" value="1" />
</bean>
</beans>
In the xml code above the generalCustomer bean is a template which hosts
common properties to other bean to inherit.
Overrride
We can override the inherited value by specify the new value in the child bean.
<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="generalCustomer" class="com.java2s.common.Customer" abstract="true">
<property name="country" value="USA" />
</bean>
<bean id="specialCustomer" parent="generalCustomer">
<property name="country" value="Japan" />
<property name="action" value="backup" />
<property name="type" value="1" />
</bean>
</beans>
Spring can do dependency checking to make sure the required properties have
been set or injected.
Spring supports four dependency checking modes.
Java Bean
The following sections uses the two Java bean as follows to shows how to use
the dependency checking.
Customer class.
package com.java2s.common;
Person class
package com.java2s.common;
dependency checking:none
The following code shows how to use spring bean configuration file with 'none'
dependency checking mode.
<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="myCustomer" class="com.java2s.common.Customer" >
<property name="action" value="buy" />
</bean>
<bean id="myPerson" class="com.java2s.common.Person">
<property name="name" value="java2s" />
<property name="address" value="address ABC" />
<property name="age" value="29" />
</bean>
</beans>
The default value to dependency checking is none. If you did not explicitly
define the dependency checking mode, it's default to 'none'. Therefore no
dependency checking will perform.
dependency checking:simple
The following code shows how to use Spring bean configuration file with
'simple' dependency checking mode.
<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="myCustomer" class="com.java2s.common.Customer"
dependency-check="simple">
<property name="person" ref="myPerson" />
<property name="action" value="buy" />
</bean>
<bean id="myPerson" class="com.java2s.common.Person">
<property name="name" value="java2s" />
<property name="address" value="address ABC" />
<property name="age" value="29" />
</bean>
</beans>
In the xml code above the myCustomer bean is marked to use simple
dependency check. For the simple dependency check, if any properties of
primitive type (int, long, double...) and collection types (map, list...) have not
been set, Spring throws UnsatisfiedDependencyException.
The 'type' property is type int which is a primitive type has not been set, an
UnsatisfiedDependencyException will throw as follows.
Spring dependency checking with
@Required Annotation
In the following we will introducing another way of doing dependency checking.
We can use @Required Annotation to add dependency checking for Java
beans.
@Required annotation can apply to a particular property.
The following Customer object has @Required in setPerson() method to make
sure the person property has been set.
package com.java2s.common;
import org.springframework.beans.factory.annotation.Required;
public class Customer
{
private Person person;
private int type;
private String action;
public Person getPerson() {
return person;
}
@Required
public void setPerson(Person person) {
this.person = person;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public String getAction() {
return action;
}
public void setAction(String action) {
this.action = action;
}
<context:annotation-config />
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<context:annotation-config />
<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.annotation.RequiredAnnotationBe
anPostProcessor"/>
<bean id="CustomerBean" class="com.java2s.common.Customer">
<property name="action" value="buy" />
<property name="type" value="1" />
</bean>
<bean id="PersonBean" class="com.java2s.common.Person">
<property name="name" value="java2s" />
<property name="address" value="address ABC" />
<property name="age" value="29" />
</bean>
</beans>
If we run it , the following error message will be throw, because person property
is unset.
org.springframework.beans.factory.BeanInitializationException:
Property 'person' is required for bean 'CustomerBean'
Define Custom @Required-Style Annotation
In Spring
We can define custom annotation to do dependency checking by using Spring
@Required-style annotation.
In the following example, we will create a custom @Required-style annotation
named @Mandatory, which is equivalent to @Required annotation.
First, we create the @Mandatory interface.
package com.java2s.common;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Mandatory {
}
Then, we apply the new created annotation to a property from a Java Bean.
package com.java2s.common;
@Mandatory
public void setPerson(Person person) {
this.person = person;
}
}
Finally, we need to register it in the xml configuration file by including
@Mandatory annotation in 'RequiredAnnotationBeanPostProcessor' class.
<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.annotation.RequiredAnnotation
BeanPostProcessor">
<property name="requiredAnnotationType" value="com.java2s.common.Mandatory
"/>
</bean>
<bean id="CustomerBean" class="com.java2s.common.Customer">
<property name="action" value="buy" />
<property name="type" value="1" />
</bean>
</beans>
Java Bean
Here's an example to show you how to use InitializingBean and
DisposableBean.
A PrinterHelper bean is defined in the following code and it implements both
InitializingBean and DisposableBean interface.
It also has two more methods one is afterPropertiesSet() method and the
other is destroy()method.
package com.java2s.common;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
public class PrinterHelper implements InitializingBean, DisposableBean
{
String message;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public void afterPropertiesSet() throws Exception {
System.out.println("Init method after properties are set : " + message);
}
public void destroy() throws Exception {
System.out.println("Spring Container is destroy! JavaBean clean up");
}
@Override
public String toString() {
return message ;
}
}
<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="printerService" class="com.java2s.common.PrinterHelper">
<property name="message" value="i'm property message" />
</bean>
</beans>
Main method
Here is the code shows how to run the code above.
ConfigurableApplicationContext.close() call will close the application context
and it will call destroy() method.
package com.java2s.common;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class App
{
public static void main( String[] args )
{
ConfigurableApplicationContext context =
new ClassPathXmlApplicationContext(new String[] {"SpringBeans.xml"});
PrinterHelper cust = (PrinterHelper)context.getBean("printerService");
System.out.println(cust);
context.close();
}
}
From the output we can see that the afterPropertiesSet() method is called,
after the message property is set and the destroy() method is call after the
context.close();
Download Java2s_Spring_Init_Destroy.zip
package com.java2s.common;
public class PrinterHelper {
String message;
<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="printerService" class="com.java2s.common.PrinterHelper"
init-method="initIt" destroy-method="cleanUp">
<property name="message" value="i'm property message" />
</bean>
</beans>
Download Java2s_Spring_init-method.zip
package com.java2s.customer.services;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
public class PrinterHelper
{
String message;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
@PostConstruct
public void initIt() throws Exception {
System.out.println("Init method after properties are set : " + message);
}
@PreDestroy
public void cleanUp() throws Exception {
System.out.println("Spring Container is destroy! Customer clean up");
}
}
<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.context.annotation.CommonAnnotationBeanPostPr
ocessor" />
<bean id="printerService" class="com.java2s.common.PrinterHelper">
<property name="message" value="i'm property message" />
</bean>
</beans>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<context:annotation-config />
<bean id="printerService" class="com.java2s.common.PrinterHelper">
<property name="message" value="i'm property message" />
</bean>
</beans>
...
<properties>
<spring.version>3.0.5.RELEASE</spring.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependencies>
...
Java Bean
The following code defines two Java beans, later we will use Spring Expression
Language to inject values into property in XML and annotation.
Server Java Bean.
package com.java2s.common;
@Override
public String toString() {
return "Server [item=" + item + ", itemName=" + itemName + "]";
}
package com.java2s.common;
Spring EL in XML
The following code shows how to use Spring EL in XML.
First, we defined a Java Bean Item in xml and set its property value. We set the
name to have itemA value and set 10 as the qty value.
Then, we created the Server bean in XML by reusing the value from Item Bean.
The Spring Expression Language is enclosed with #{ expression }. The
following code references the value from Item bean. It assigns the itemBean to
item and itemBean.name to itemName. Value of itemBean.name is itemA.
<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-3.0.xsd">
<bean id="itemBean" class="com.java2s.common.Item">
<property name="name" value="itemA" />
<property name="qty" value="10" />
</bean>
<bean id="myServer" class="com.java2s.common.Server">
<property name="item" value="#{itemBean}" />
<property name="itemName" value="#{itemBean.name}" />
</bean>
</beans>
Download Java2s_Spring_EL_XML.zip
Spring EL in Annotation
The following example shows how to use Spring Expression Language in
annotation.
First, we define a Java Bean Item and mark it with Component annotation. For its
properties we use the Value annotation to assign them values
package com.java2s.common;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component("itemBean")
public class Item {
@Value("itemA") //inject String directly
private String name;
@Value("10") //inject interger directly
private int qty;
public String getName() {
return name;
}
@Override
public String toString() {
return "Item [name=" + name + ", qty=" + qty + "]";
}
public int getQty() {
return qty;
}
public void setQty(int qty) {
this.qty = qty;
}
public void setName(String name) {
this.name = name;
}
}
package com.java2s.common;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component("myServer")
public class Server {
@Value("#{itemBean}")
private Item item;
@Value("#{itemBean.name}")
private String itemName;
@Override
public String toString() {
return "Server [item=" + item + ", itemName=" + itemName + "]";
}
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
</beans>
Example
The following code shows how to run the code above.
package com.java2s.common;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class App {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("SpringBea
ns.xml");
Server obj = (Server) context.getBean("myServer");
System.out.println(obj);
}
}
Download Java2s_spring_EL_Annotation.zip
package com.java2s.common;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Component;
@Component("testBean")
public class Test {
public Test() {
map = new HashMap<String, String>();
map.put("MapA", "This is A");
map.put("MapB", "This is B");
map.put("MapC", "This is C");
package com.java2s.common;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component("customerBean")
public class Customer {
@Value("#{testBean.map['MapA']}")
private String mapA;
@Value("#{testBean.list[0]}")
private String list;
<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-3.0.xsd">
</beans>
bean.property_name
Example
The following code defines an Address bean and marks the bean with Spring
Expression Language.
It fills the street with string value, fills the postcode with int value. It also defines
a utility method getFullAddress to return the full address from post code,
street, and country.
package com.java2s.core;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component("addressBean")
public class Address {
@Value("123456")
private int postcode;
@Value("US")
private String country;
The following code uses the value defined in the Address Java bean to fill the
properties in the Server bean.
In Spring Expression language we can also call the method from a bean.
package com.java2s.core;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component("myServer")
public class Server {
@Value("#{addressBean}")
private Address address;
@Value("#{addressBean.country}")
private String country;
@Value("#{addressBean.getFullAddress('java2s')}")
private String fullAddress;
@Override
public String toString() {
return "Server [address=" + address + "\n, country=" + country
+ "\n, fullAddress=" + fullAddress + "]";
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getFullAddress() {
return fullAddress;
}
public void setFullAddress(String fullAddress) {
this.fullAddress = fullAddress;
}
}
The following code shows how to fill the same data in xml file configuration.
<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-3.0.xsd">
<bean id="myServer" class="com.java2s.core.Server">
<property name="address" value="#{addressBean}" />
<property name="country" value="#{addressBean.country}" />
<property name="fullAddress" value="#{addressBean.getFullAddress('java2s')}"
/>
</bean>
<bean id="addressBean" class="com.java2s.core.Address">
<property name="street" value="Main Street, New York" />
<property name="postcode" value="123456" />
<property name="country" value="US" />
</bean>
</beans>
Test
<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-3.0.xsd">
<bean id="myServer" class="com.java2s.core.Server">
</bean>
</beans>
package com.java2s.core;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class App {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("SpringBea
ns.xml");
Server obj = (Server) context.getBean("myServer");
System.out.println(obj);
}
}
Example 2
The following code shows how to call a method with no parameter in Spring
Expression Language.
First, we define a Java bean with a method to return a double value.
package com.java2s.core;
import org.springframework.stereotype.Component;
@Component("priceBean")
public class Price {
public double getSpecialPrice() {
return new Double(99.99);
}
}
In the following code we call the method defined above in Spring Expression
Language.
@Value("#{priceBean.getSpecialPrice()}")
private double amount;
@Value("#{'java2s'.toUpperCase()}")
private String name;
package com.java2s.core;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component("myServer")
public class Server {
@Value("#{'java2s'.toUpperCase()}")
private String name;
@Value("#{priceBean.getSpecialPrice()}")
private double amount;
@Override
public String toString() {
return "Server [name=" + name + ", amount=" + amount + "]";
}
The following code shows how to rewrite the code above in bean definition XML
file.
<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-3.0.xsd">
</beans>
equal: ==, eq
not equal: !=, ne
less than: <, lt
less than or equal: <= , le
greater than: >, gt
greater than or equal: >=, ge
and
or
not (!)
addition (+)
Subtraction (-)
Multiplication (*)
Division (/)
Modulus (%)
Exponential power (^)
Example
The following code shows how to use operators from Spring expression
language.
package com.java2s.core;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component("customerBean")
public class Server {
//Relational operators
//Mathematical operators
<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-3.0.xsd">
<bean id="customerBean" class="com.java2s.core.Customer">
<property name="testEqual" value="#{1 == 1}" />
<property name="testNotEqual" value="#{1 != 1}" />
<property name="testLessThan" value="#{1 lt 1}" />
<property name="testLessThanOrEqual" value="#{1 le 1}" />
<property name="testGreaterThan" value="#{1 > 1}" />
<property name="testGreaterThanOrEqual" value="#{1 >= 1}" />
If condition is true it will execute the trueAction, if the the condition is false it
will run the falseAction.
The following Java bean has a property value for qtyOnHand whose value is 99.
package com.java2s.core;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component("itemBean")
public class Item {
@Value("99")
private int qtyOnHand;
}
package com.java2s.core;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component("customerBean")
public class Customer {
The following xml configuration file shows how to use tenary operator in xml
markup.
<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-3.0.xsd">
package com.java2s.core;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component("emailBean")
public class Email {
@Value("your email here")
String emailAddress;
}
The following codes use regular expression to validate a number and stores the
result in boolean value.
// if this is a digit?
@Value("#{'1' matches '\\d+' }")
private boolean validDigit;
The following code uses regular expression to validate an email address from
another Java bean.
...
<bean id="customerBean" class="com.java2s.core.Customer">
<property name="validDigit" value="#{'1' matches '\d+' }" />
<property name="msg"
value="#{ ('abc' matches '\d+') == true ? 'yes this is digit' : 'No this is
not a digit' }" />
<property name="validEmail"
value="#{emailBean.emailAddress matches '^[_A-Za-z0-9-]+(\.[_A-Za-z0-9-]+)*@
[A-Za-z0-9]+(\.[A-Za-z0-9]+)*(\.[A-Za-z]{2,})$' }" />
</bean>
</beans>
Spring can auto scan, detect, wire and instantiate Java beans.
The following sections shows the difference between xml configuration vs auto
scan auto wire configuration.
Old fashion
Here is a normal Java bean.
package com.java2s.common;
package com.java2s.common;
@Override
public String toString() {
return "PrinterHelper [myPrinter=" + printer + "]";
}
}
<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="printerHelper" class="com.java2s.common.PrinterHelper">
<property name="printer" ref="myPrinter" />
</bean>
<bean id="myPrinter" class="com.java2s.common.Printer" />
</beans>
package com.java2s.common;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
Download Java2s_Spring_Not_Autowired.zip
package com.java2s.common;
import org.springframework.stereotype.Component;
@Component
public class Printer
{
}
The following Java bean uses not only @Component to indicate this is an auto
scan component, it also marks the property as Autowired.
package com.java2s.common;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class PrinterHelper
{
@Autowired
Printer myPrinter;
}
The following xml configuration file finally adds the package to enable the auto
wire auto scan context.
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<context:component-scan base-package="com.java2s.common" />
</beans>
Download Java2s_Spring_Autowire.zip
Note
By default, Spring will lower case the first character of the component's simple
class name as the bean id.
The following code shows how to use the auto-generated id to retrieve the
component.
@Component("myService")
public class PrinterHelper {
}
Once we define the name in @Component, we can retrieve it with this name
'myService'.
Filter to include
The following code shows how to use Spring filter to scan and register
components by regular expressions, even the class is not annotated with
@Component.
package com.java2s.common;
public class Printer
{
}
Helper class
package com.java2s.common;
import org.springframework.beans.factory.annotation.Autowired;
The following xml configuration uses the Spring filter to include classes.
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<context:include-filter type="regex"
expression="com.java2s.common.*DAO.*" />
Run it
package com.java2s.common;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.java2s.customer.services.PrinterHelper;
public class App
{
public static void main( String[] args )
{
ApplicationContext context =
new ClassPathXmlApplicationContext(new String[] {"SpringBeans.xml"});
PrinterHelper cust = (PrinterHelper)context.getBean("printerHelper");
System.out.println(cust);
}
}
Filter to exclude
The following code shows how to exclude specified components to stop Spring
from auto registering for classes annotated with @Service.
Spring can use @Autowired annotation to auto wire bean on the setter method,
constructor or a field.
Java Beans
The following code defines two Java beans.
package com.java2s.common;
public class JobTitle
{
@Override
public String toString() {
return "JobTitle [person=" + person + ", type=" + type + ", action="
+ action + "]";
}
public Employee getPerson() {
return person;
}
public void setPerson(Employee person) {
this.person = person;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public String getAction() {
return action;
}
public void setAction(String action) {
this.action = action;
}
private Employee person;
private int type;
private String action;
}
Employee Bean
package com.java2s.common;
public class Employee{
private String name;
private String address;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Employee [name=" + name + ", address=" + address + ", age="
+ age + "]";
}
}
enable @Autowired
To enable @Autowired, we have to register
'AutowiredAnnotationBeanPostProcessor'. And we can do that in two ways.
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<context:annotation-config />
</beans>
<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.annotation.AutowiredAnnotationBeanP
ostProcessor"/>
</beans>
package com.java2s.common;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
Download Java2s_Spring_autowire_1.zip
@Autowired Examples
The following code shows how to autowire bean via @Autowired on setter
method
package com.java2s.common;
import org.springframework.beans.factory.annotation.Autowired;
package com.java2s.common;
import org.springframework.beans.factory.annotation.Autowired;
The following code shows how to autowire bean via @Autowired on a field.
package com.java2s.common;
import org.springframework.beans.factory.annotation.Autowired;
All of the above three methods autowired Employee Java bean into JobTitle's
person property.
Example
Here is the code to run the code above.
package com.java2s.common;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
}
}
Output:
Download Java2s_Spring_Autowire_Setter.zip
Dependency checking
By default @Autowired annotation performs the dependency checking to
ensure the autowired bean exist.
If Spring can't find a matching bean, it will throw an exception. To disable
@Autowired dependency check, set the "required" attribute of @Autowired to
false.
import org.springframework.beans.factory.annotation.Autowired;
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<context:annotation-config />
</beans>
package com.java2s.common;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
Spring can wire beans automatically. To enable it, define the "autowire"
attribute in <bean>.
package com.java2s.common;
public class Customer
{
private Person person;
public Customer(Person person) {
this.person = person;
}
public void setPerson(Person person) {
this.person = person;
}
}
package com.java2s.common;
public class Person
{
}
Auto-Wiring 'no'
This is the default mode, we need to wire the Java bean via 'ref' attribute.
Auto-Wiring 'byName'
The following code add autowire byName to the bean declaration.
Since the name of "person" bean is same with the name of the "customer"
bean's "person" property, Spring will auto wire it via method setPerson(Person
person).
Auto-Wiring 'byType'
The following xml configuration declares the autowire type as byType.
Since the data type of "person" bean is same as the data type of the "customer"
bean's property person object, Spring will auto wire it via method
setPerson(Person person).
Auto-Wiring 'constructor'
The following code declares a bean's autowire type as constructor.
The data type of "person" bean is same as the constructor argument data type
in "customer" bean's property (Person object), Spring will auto wire it via
constructor method - "public Customer(Person person)".
Since there is a constructor in "Customer" class, Spring will auto wire it via
constructor method - "public Customer(Person person)".
Besides Dependency Injection (DI), another core feature that the Spring
Framework offers is aspect-oriented programming (AOP).
AOP is a tool for implementing crosscutting concerns.
The crosscutting concerns refers to logic in an application that cannot be
decomposed from the rest of the application and may result in code duplication
and tight coupling.
AOP is a programming paradigm that aims to increase modularity by allowing
the separation of cross-cutting concerns.
Adding Log methods to every single method is a cross-cutting concern. A
logging strategy affects every logged part of the system. The log methods
would cross-cut all logged classes and methods.
Spring AOP framework modularizes cross-cutting concerns in aspects. When
executing a method in Spring IoC container, Spring AOP can hijack the
executing method, and add extra functionality before or after the method
execution.
AOP Concepts
AOP comes with its own specific set of concepts and terms.
The following are the core concepts of AOP:
Joinpoints is a point during the execution of your application. Typical example of
joinpoints is a call to a method. Joinpoints define the points in your application at which
you can insert additional logic using AOP.
Advice is the code executed at a particular joinpoint. There are many types of advice,
such as before , which executes before the joinpoint, and after , which executes after it.
Pointcut is a collection of joinpoints that is used to define when advice should be
executed. By creating pointcuts, we control over how to apply advice to the Java Bean
in the application.
Weaving is the process of inserting aspects into the application code at the appropriate
point.
An object whose execution flow is modified by an AOP process is referred to as the
target object or advised object.
dependency
Add the following new dependency for AOP coding to POM.xml.
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>2.2.2</version>
</dependency>
Java Bean
The following code defines a Java bean for a printer service.
package com.java2s.common;
XML configuration
Here is the Spring-Customer.xml file for bean configuration.
<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="myService" class="com.java2s.common.PrinterService">
<property name="name" value="printerName" />
<property name="url" value="http://www.java2s.com" />
</bean>
</beans>
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
Output
Download Java2s_Spring_Pre_AOP.zip
Before advice
The following code shows how to add Before advice.
A Before advice is executed before the method execution.
First, create a class which implements MethodBeforeAdvice interface.
package com.java2s.common;
import java.lang.reflect.Method;
import org.springframework.aop.MethodBeforeAdvice;
<bean id="myServiceProxy"
class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="interceptorNames">
<list>
<value>aopBeforeMethodBean</value>
</list>
</property>
</bean>
<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="myService" class="com.java2s.common.PrinterService">
<property name="name" value="printerName" />
<property name="url" value="http://www.java2s.com" />
</bean>
<bean id="myServiceProxy"
class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="interceptorNames">
<list>
<value>aopBeforeMethodBean</value>
</list>
</property>
</bean>
</beans>
From the result we can see that the AOPBeforeMethod's before() method is
executed before every myService's methods.
package com.java2s.common;
import java.lang.reflect.Method;
import org.springframework.aop.AfterReturningAdvice;
<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="myServiceProxy"
class="org.springframework.aop.framework.ProxyFactoryBean">
From the result we can see that the AOPAfterMethod's afterReturning() method
is executed after every myService's methods returns a result.
package com.java2s.common;
import org.springframework.aop.ThrowsAdvice;
<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="myServiceProxy"
class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="interceptorNames">
<list>
<value>aopThrowExceptionBean</value>
</list>
</property>
</bean>
</beans>
From the result we can see that Spring IoC container runs the
AOPThrowException's afterThrowing() method when myService's methods
throws an exception.
Around advice
The following code shows how to use Around advice. Around advice combines
all three advices above, and execute during method execution.
First, create a class which implements MethodInterceptor interface.
public Object invoke(MethodInvocation methodInvocation) throws Throwable
method is called for each method call and we have to call the
"methodInvocation.proceed();" to run the original method, otherwise the original
method will not run.
package com.java2s.common;
import java.util.Arrays;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
try {
// proceed to original method call
Object result = methodInvocation.proceed();
return result;
} catch (IllegalArgumentException e) {
System.out.println("AOPAroundMethod : Throw exception call.");
throw e;
}
}
}
Here is the xml Bean configuration file to install the Around Advice AOP.
<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="myServiceProxy"
class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="interceptorNames">
<list>
<value>aopAroundMethodBean</value>
</list>
</property>
</bean>
</beans>
The following code shows how to use Castor to do Java Object to XML
Mapping.
Project Dependency
In order to use castor, add the following dependencies to pom.xml file.
<properties>
<spring.version>3.0.5.RELEASE</spring.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
</dependencies>
Java Bean
Here is a simple Java bean for doing the xml mapping
package com.java2s.common;
String name;
int age;
boolean trained;
String address;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public boolean isTrained() {
return trained;
}
public void setTrained(boolean trained) {
this.trained = trained;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
package com.java2s.common;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.springframework.oxm.Marshaller;
import org.springframework.oxm.Unmarshaller;
FileOutputStream os = null;
try {
os = new FileOutputStream(filepath);
getMarshaller().marshal(object, new StreamResult(os));
} finally {
if (os != null) {
os.close();
}
}
}
FileInputStream is = null;
try {
is = new FileInputStream(xmlfile);
return getUnmarshaller().unmarshal(new StreamSource(is));
} finally {
if (is != null) {
is.close();
}
}
}
}
Spring Configuration
In Spring's bean configuration file, inject CastorMarshaller as the XML binding
framework.
<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-3.0.xsd">
</beans>
Example
Here is the code run the application.
package com.java2s.common;
import java.io.IOException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
}
}
The following XML file "customer.xml" is generated in the project root folder.
File : customer.xml
<mapping>
<class name="com.java2s.core.model.Employee">
<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-3.0.xsd">
</beans>
Links
http://www.java2s.com/Tutorials/Java/Spring/index.htm