Spring Notes I

  • Introduction

Inversion of Control (IoC): The core of the Spring framework is based on the principle of IoC. IoC is a technique that externalizes the creation and management of component dependencies.

A alternative descriptive name is Dependency Injection (DI). Such behavior takes place at runtime, in which an instance of class A is provided to class B by some external process if B depends on A to perform some processing.

Aspect Oriented Programing (AOP): AOP provids another way of thinking about program structure. The key unit of modularity in OOP is the class, whereas in AOP the unit of modularity is the aspect. Aspects enable the modularization of concerns such as transaction management, log management, and input field validation that cut across multiple types and objects.

The best document: Spring Framework Documents

  • Spring Basics

  • applicationContext.xml
  • It’s a IOC container like BeanFactory with more extensions
  • Doesn’t have to be named applicationContext.xml
  • A simple view of Spring is that it is Hashmap of objects
    • Objects are name/value pairs
  • It can be used as a simple Registry
  • There are namespaces that aid in configuration and validation
ApplicationContext appContext = new ClassPathXmlApplicationContext(new String[]{“applicationContext.xml”});

Object obj = appContext.getBean("Object", Object.class)

Import multiple configuration files

<beans>  
<import resource=”spring-dao.xml”/>
<import resource=”spring-service.xml”/>
<import resource=”spring-action.xml”/>
...
<bean>
</bean>
...
</beans>
  • Beans
  • Essentially classes
  • Defining beans replaces using the keyword “new”
  • Define the class by using the interface

  • Id or Name

    • Can be used interchaneably
    • Id has to be a valid XML identifier
    • Name can contain special characters
  • Constructor Args
    • Used to refernce properties of the constructor
  • Properties
    • Getters and Setters of the POJO
  • References
    • Ref. to other beans that we have defined
  • Values

    • Basic primitive values that are setting on POJO
  • Default No-Args Constructor

    • Setter Injection v.s. Constructor Injection
  • Setter Injection

The class should provide corresponding setters and getters. Setter injection is more common.

<bean id="..." class="...">  
<property name="prop1" value="" ref=""/>
<property name="prop2" value="" ref=""/>
...
</bean>

  • Constructor Injection

The class should provide appropriate class constructor. Constructor injection guarantees the contract.

<bean id="..." class="...">  
<constructor-arg>para1</constructor-arg>
<constructor-arg>para2</constructor-arg>
<constructor-arg index="0" ref=""/>
...
</bean>

Index field indicates the arguments’ indexes.

  • Autowiring
  • Spring can automatically wire beans together
  • byType
    • Allows a property to be autowired if exactly one bean of the property type exists in the container. A fatal exception is thrown if more than one exists.
  • byName
    • By property name. Spring looks for a bean with the same name as the property that needs to be autowired
  • Constructor
    • Similar to byType, but applies to constructor arguments.

For example,

<!--need appropriate constructor-->
<bean id="..." class="..." autowire="constructor" />

<!--need default constructor and setter-->
<bean id="..." class="..." autowire="byType" />
<!--looking for the type of setter's parameter-->
<!--need default constructor and setter-->
<bean id="..." class="..." autowire="byName" />
<!--looking for setter's name-->
  • Set Injection
<bean id="..." class="...">  
<!--set or list-->
<set>
<value>value1</value>
<value>value2</value>
</set>
</bean>
<bean id="..." class="...">  
<!--map-->
<map>
<entry key="k1" value="">
<entry key="k2" value="">
</map>
</bean>
<bean id="..." class="...">  
<!--properties-->
<props>
<prop key="k1" value=""/>
<prop key="k2" value=""/>
</props>
</bean>
  • Spring Annotation

  • Part of the context namespace
xmlns:context="http://www.springframework.org/schema/context"

xsi:schemaLocation="http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd"
  • Two elements have to be configured
<context:annotation-config>  

<context:component-scan base-package="com.projectname"/>
  • Stereotype Annotation
  • @Component
    • Regular components / beans, any POJO
  • @Service
    • Service tier where business logic is contained
    • e.g. @Service("customerService")
  • @Controller
    • Control layer / actions
  • @Repository

    • Data access tier / database interaction layer
    • e.g. @Repository("userDao")
  • Autowired

    • member variables

      @Autowired
      private CustomerRepository customerRepository;

      uses reflection to set it

    • Constructor

    • Setter

      call the actual setter

  • Java Configuration

  • No XML
  • @Configuration is a class level annotation
  • @Bean is a method level annotation
@Configuration
public class AppConfig{
@Bean(name = "customerService")
public CustomerService getCustomerService(){
return new CustomerServiceImpl();
}
}
ApplicationContext appContext = new AnnotationConfigApplicationContext(AppConfig.class);
  • Autowired

    • @ComponentScan({"com.xxx"}), class level annotation
  • Singleton Scope

    • @Scope("singleton")
  • Prototype Scope

    • @Scope("prototype")
    • A new instance per request
  • Web Scopes

    • Refer to Spring MVC
  • Request
    • Return a single bean per HTTP Request
  • Session
    • Return a single bean per HTTP Session
  • GlobalSession
    • Return a single bean per per Application
  • Spring Boot

Spring boot makes it easy to create stand-alone, production-grade Spring based Applications that you can “just run”. Most Spring Boot applications need very little Spring configuration.

Features:

  1. Create stand-alone Spring applications
  2. Embed Tomcat, Jetty or Undertow directly (no need to deploy WAR files)
  3. Provide opinionated ‘starter’ POMs to simplify your Maven configuration
  4. Automatically configure Spring whenever possible
  5. Provide production-ready features such as metrics and health checks
  6. Absolutely no code generation and no requirement for XML configuration

Configuration of spring boot in pom.xml

<!-- Spring Boot : parent dependency -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.6.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>

Create a controller

@Controller
@EnableAutoConfiguration
public class DoSthController {
@RequestMapping("/")
public int divide(int a, int b) {
return a / b;
}
//// create a main funtion to run here
//public static void main(String[] args) throws Exception {
// SpringApplication.run(DoSthController.class, args);
//}
}

Or create an seperate spring application

@SpringBootApplication
public class DoSthApplication {
public static void main(String[] args) {
SpringApplication.run(DoSthApplication.class, args);
}
}

Create a unit test

public class DoSthControllerTest {
@Test
public void testDivide_success() {
assertEquals(1, new DoSthController().divide(5, 5));
}

@Test(expected = Exception.class)
public void testDivide_fail() throws Exception {
DoSthController doSth = new DoSthController();
doSth.divide(5, 0);
}
}

Start Tomcat, then right-click and run DoSthApplication, or just run the test class and the test methods.