Skip to content
Thomas Czogalik edited this page Nov 27, 2020 · 15 revisions

Spring

Uses dependancy injection

  • Object or service provides dependancy for another object
  • object or service is provided instead of created or searched by client

Terminology

Spring Container

provides infrastructure for SpringBeans to live

BeanFactory/ApplicationContext

Bean instantiation/wiring

use ApplicationContext instead BeanFactory

SpringBean

Object that is init/config/managed by SpringContainer

vs JavaBeans

must not implement serializable

may have arguments in constructor

Injections

Import xml into another

<import resource="classpath:spring-config.xml" />

setter

<property name={id} value={class name}/>

constructor

<constructor-arg value={argument value}/>

//index i sets i-th argument of constructor 
<constructor-arg index={i} value={argument value}/>

object

<property name={id} ref={object id}/>/>

Collection

  1. is for List
<property name="bookList">
      	<list>
      	    <ref bean="book1"/>
      	    <ref bean="book2"/>
      	</list>
</property> 
  1. is for Set
  2. is for Map
<property name="myMap">
	 <map>
            <entry key="0" value="Map Value A"/>           
            <entry key="1" value="Map Value B"/>
         </map>
</property> 
  1. is for Properties
<property name="myProp">
	<props>
	    <prop key="propKeyA">Prop Value A</prop>
	    <prop key="propKeyB">Prop Value B</prop>
	</props>
</property>     

control the scope of the objects created from a particular bean definition

@Scope("prototype")
@Repository
public class MovieFinderImpl implements MovieFinder {
    // ...
}

singleton

(Default) Scopes a single bean definition to a single object instance for each Spring IoC container. Use for stateless beans.

prototype

Scopes a single bean definition to any number of object instances. Use for statefull beans.

request

Scopes a single bean definition to the lifecycle of a single HTTP request. That is, each HTTP request has its own instance of a bean created off the back of a single bean definition. Only valid in the context of a web-aware Spring ApplicationContext.

session

Scopes a single bean definition to the lifecycle of an HTTP Session. Only valid in the context of a web-aware Spring ApplicationContext.

application

Scopes a single bean definition to the lifecycle of a ServletContext. Only valid in the context of a web-aware Spring ApplicationContext.

websocket

Scopes a single bean definition to the lifecycle of a WebSocket. Only valid in the context of a web-aware Spring ApplicationContext.

  • A child bean definition inherits configuration data from a parent definition.
  • A child bean definition inherits scope, constructor argument values, property values, and method overrides from the parent, with the option to add new values
  • The child definition can override some values or add others as needed


<bean id="inheritedTestBean" abstract="true"
        class="org.springframework.beans.TestBean">
    <property name="name" value="parent"/>
    <property name="age" value="1"/>
</bean>

<bean id="inheritsWithDifferentClass"
        class="org.springframework.beans.DerivedTestBean"
        parent="inheritedTestBean" init-method="initialize">  
    <property name="name" value="override"/>
    <!-- the age property value of 1 will be inherited from parent -->
</bean>

Lifecycle Callback

interact with the container’s management of the bean lifecycle

use init-method and destroy-method in bean definition metadata to not couple to Spring

<bean id="exampleInitBean" class="examples.ExampleBean" init-method="init"/>

public class ExampleBean {

    public void init() {
        // do some initialization work
    }
}

@PostConstruct and @PreDestroy annotations are generally considered best practice

public class ExampleBean {

    @PostConstruct
    public void init() {
        // do some initialization work
    }
}

BeanPostProcessor

If you want to implement some custom logic after the Spring container finishes instantiating, configuring, and initializing a bean, you can plug in one or more custom BeanPostProcessor implementations.

implement BeanPostProcessor

  • afterInit Method
  • beforeInit Method
  • return of methods needs to be the object passed as argument
  • register my BeanPostProcessor as bean, but without id

Annotations

@Required

  • applies to bean property setter methods
  • indicates that the affected bean property must be populated at configuration time, through an explicit property value in a bean definition or through autowiring
  • allows for eager and explicit failure
public class SimpleMovieLister {

    private MovieFinder movieFinder;

    @Required
    public void setMovieFinder(MovieFinder movieFinder) {
        this.movieFinder = movieFinder;
    }

    // ...
}

@Autowired /@Inject

will tell Spring to search for a Spring bean which implements the required interface and place it automatically into the setter.

note: @Autowired is Spring's own (legacy) annotation. @Inject is part of @javax.inject.Inject that defines a standard for dependency injection similar to Spring.

@Resource

  • identify a specific target component by its unique name
  • If no name is explicitly specified, the default name is derived from the field name or setter method

Value

can be used for injecting default values

public TestBean testMethod(@Value("#{properties.test.value}") String value) { ... }

Stereotypes

@Component

  • is a generic stereotype for any Spring-managed component
  • Annotate other components (for example REST resource classes) with component stereotype

@Repository

  • DAO class
  • all database access logic should be in DAO classes.

@Service

  • is a service class
  • All business logic is in Service classes
  • Generally methods of service layer are covered under transaction
  • You can make multiple DAO calls from service method, if one transaction fails all transactions should rollback

Reason to use

  • easy to write an AOP pointcut that targets, for instance, all classes annotated with @Repository
  • don't have to write bean definitions in context xml file. Instead annotate classes and use those by autowiring
  • Specialized annotations help to clearly demarcate application layers (in a standard 3 tiers application).

Cron

  • in Scheduled tasks
  • CronSequenceGenerator returns next execution date
  • Get time between two executions
CronSequenceGenerator cronSequenceGenerator = new CronSequenceGenerator("0 0 5 * * *");
Date next = cronSequenceGenerator.next(new Date());
Date next2 = cronSequenceGenerator.next(next);
LocalDateTime localDateTime = DateUtils.convertDateToUTCLocalDateTime(next);
LocalDateTime localDateTime2 = DateUtils.convertDateToUTCLocalDateTime(next2);
long between = ChronoUnit.SECONDS.between(localDateTime, localDateTime2);
Clone this wiki locally