,

The Java Programming language provided support for Annotations from Java 5.0. Leading Java frameworks were quick to adopt annotations and the Spring Framework started using annotations from the release 2.5. Due to the way they are defined, annotations provide a lot of context in their declaration.

Prior to annotations, the behavior of the Spring Framework was largely controlled through XML configuration. Today, the use of annotations provide us tremendous capabilities in how we configure the behaviours of the Spring Framework.

In this post, we’ll take a look at the annotations available in the Spring Framework.

Core Spring Framework Annotations

@Required

This annotation is applied on bean setter methods. Consider a scenario where you need to enforce a required property. The @Required annotation indicates that the affected bean must be populated at configuration time with the required property. Otherwise an exception of type BeanInitializationException is thrown.

@Autowired

This annotation is applied on fields, setter methods, and constructors. The @Autowired annotation injects object dependency implicitly.

When you use @Autowired on fields and pass the values for the fields using the property name, Spring will automatically assign the fields with the passed values.

You can even use @Autowired  on private properties, as shown below. (This is a very poor practice though!)

When you use @Autowired on setter methods, Spring tries to perform the by Type autowiring on the method. You are instructing Spring that it should initiate this property using setter method where you can add your custom code, like initializing any other property with this property.

Consider a scenario where you need instance of class A, but you do not store A in the field of the class. You just use A to obtain instance of B, and you are storing B in this field. In this case setter method autowiring will better suite you. You will not have class level unused fields.

When you use @Autowired on a constructor, constructor injection happens at the time of object creation. It indicates the constructor to autowire when used as a bean. One thing to note here is that only one constructor of any bean class can carry the @Autowired annotation.

NOTE: As of Spring 4.3, @Autowired  became optional on classes with a single constructor. In the above example, Spring would still inject an instance of the Person  class if you omitted the @Autowired  annotation.

@Qualifier

This annotation is used along with @Autowired annotation. When you need more control of the dependency injection process, @Qualifier can be used. @Qualifier can be specified on individual constructor arguments or method parameters. This annotation is used to avoid confusion which occurs when you create more than one bean of the same type and want to wire only one of them with a property.

Consider an example where an interface BeanInterface is implemented by two beans BeanB1 and BeanB2.

Now if BeanA autowires this interface, Spring will not know which one of the two implementations to inject.
One solution to this problem is the use of the @Qualifier annotation.

With the @Qualifier annotation added, Spring will now know which bean to autowire where beanB2 is the name of BeanB2.

@Configuration

This annotation is used on classes which define beans. @Configuration is an analog for XML configuration file – it is configuration using Java class. Java class annotated with @Configuration is a configuration by itself and will have methods to instantiate and configure the dependencies.

Here is an example:

@ComponentScan

This annotation is used with @Configuration annotation to allow Spring to know the packages to scan for annotated components. @ComponentScan is also used to specify base packages using basePackageClasses or basePackage attributes to scan. If specific packages are not defined, scanning will occur from the package of the class that declares this annotation.

Checkout this post for an in depth look at the Component Scan annotation.

@Bean

This annotation is used at the method level. @Bean annotation works with @Configuration to create Spring beans. As mentioned earlier, @Configuration will have methods to instantiate and configure dependencies. Such methods will be annotated with @Bean. The method annotated with this annotation works as bean ID and it creates and returns the actual bean.

Here is an example:

@Lazy

This annotation is used on component classes. By default all autowired dependencies are created and configured at startup. But if you want to initialize a bean lazily, you can use @Lazy annotation over the class. This means that the bean will be created and initialized only when it is first requested for. You can also use this annotation on @Configuration classes. This indicates that all @Bean methods within that @Configuration should be lazily initialized.

@Value

This annotation is used at the field, constructor parameter, and method parameter level. The @Value annotation indicates a default value expression for the field or parameter to initialize the property with. As the @Autowired annotation tells Spring to inject object into another when it loads your application context, you can also use @Value annotation to inject values from a property file into a bean’s attribute. It supports both #{...} and ${...} placeholders.

Spring Framework Stereotype Annotations

@Component

This annotation is used on classes to indicate a Spring component. The @Component annotation marks the Java class as a bean or say component so that the component-scanning mechanism of Spring can add into the application context.

@Controller

The @Controller  annotation is used to indicate the class is a Spring controller. This annotation can be used to identify controllers for Spring MVC or Spring WebFlux.

@Service

This annotation is used on a class. The @Service marks a Java class that performs some service, such as execute business logic, perform calculations and call external APIs. This annotation is a specialized form of the @Component annotation intended to be used in the service layer.

@Repository

This annotation is used on Java classes which directly access the database. The @Repository annotation works as marker for any class that fulfills the role of repository or Data Access Object.

This annotation has a automatic translation feature. For example, when an exception occurs in the @Repository there is a handler for that exception and there is no need to add a try catch block.

Spring Boot Annotations

@EnableAutoConfiguration

This annotation is usually placed on the main application class. The @EnableAutoConfiguration annotation implicitly defines a base “search package”. This annotation tells Spring Boot to start adding beans based on classpath settings, other beans, and various property settings.

@SpringBootApplication

This annotation is used on the application class while setting up a Spring Boot project. The class that is annotated with the @SpringBootApplication must be kept in the base package. The one thing that the @SpringBootApplication does is a component scan. But it will scan only its sub-packages. As an example, if you put the class annotated with @SpringBootApplication in com.example then @SpringBootApplication will scan all its sub-packages, such as com.example.a, com.example.b, and com.example.a.x.

The @SpringBootApplication is a convenient annotation that adds all the following:

  • @Configuration
  • @EnableAutoConfiguration
  • @ComponentScan

Spring MVC and REST Annotations

@Controller

This annotation is used on Java classes that play the role of controller in your application. The @Controller annotation allows autodetection of component classes in the classpath and auto-registering bean definitions for them. To enable autodetection of such annotated controllers, you can add component scanning to your configuration. The Java class annotated with @Controller is capable of handling multiple request mappings.

This annotation can be used with Spring MVC and Spring WebFlux.

@RequestMapping

This annotation is used both at class and method level. The @RequestMapping annotation is used to map web requests onto specific handler classes and handler methods. When @RequestMapping is used on class level it creates a base URI for which the controller will be used. When this annotation is used on methods it will give you the URI on which the handler methods will be executed. From this you can infer that the class level request mapping will remain the same whereas each handler method will have their own request mapping.

Sometimes you may want to perform different operations based on the HTTP method used, even though the request URI may remain the same. In such situations, you can use the method attribute of @RequestMapping with an HTTP method value to narrow down the HTTP methods in order to invoke the methods of your class.

Here is a basic example on how a controller along with request mappings work:

In this example only GET requests to /welcome is handled by the welcomeAll() method.

This annotation also can be used with Spring MVC and Spring WebFlux.

The @RequestMapping  annotation is very versatile. Please see my in depth post on Request Mapping bere.

@CookieValue

This annotation is used at method parameter level. @CookieValue is used as argument of request mapping method. The HTTP cookie is bound to the @CookieValue parameter for a given cookie name. This annotation is used in the method annotated with @RequestMapping.
Let us consider that the following cookie value is received with a http request:

JSESSIONID=418AB76CD83EF94U85YD34W

To get the value of the cookie, use @CookieValue like this:

@CrossOrigin

This annotation is used both at class and method level to enable cross origin requests. In many cases the host that serves JavaScript will be different from the host that serves the data. In such a case Cross Origin Resource Sharing (CORS) enables cross-domain communication. To enable this communication you just need to add the @CrossOrigin annotation.

By default the @CrossOrigin annotation allows all origin, all headers, the HTTP methods specified in the @RequestMapping annotation and maxAge of 30 min. You can customize the behavior by specifying the corresponding attribute values.

An example to use @CrossOrigin at both controller and handler method levels is this.

In this example, both getExample() and getNote() methods will have a maxAge of 3600 seconds. Also, getExample() will only allow cross-origin requests from http://example.com, while getNote() will allow cross-origin requests from all hosts.

Composed @RequestMapping Variants

Spring framework 4.3 introduced the following method-level variants of @RequestMapping annotation to better express the semantics of the annotated methods. Using these annotations have become the standard ways of defining the endpoints. They act as wrapper to @RequestMapping.

These annotations can be used with Spring MVC and Spring WebFlux.

@GetMapping

This annotation is used for mapping HTTP GET requests onto specific handler methods. @GetMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.GET)

@PostMapping

This annotation is used for mapping HTTP POST requests onto specific handler methods. @PostMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.POST)

@PutMapping

This annotation is used for mapping HTTP PUT requests onto specific handler methods. @PutMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.PUT)

@PatchMapping

This annotation is used for mapping HTTP PATCH requests onto specific handler methods. @PatchMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.PATCH)

@DeleteMapping

This annotation is used for mapping HTTP DELETE requests onto specific handler methods. @DeleteMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.DELETE)


@ExceptionHandler

This annotation is used at method levels to handle exception at the controller level. The @ExceptionHandler annotation is used to define the class of exception it will catch. You can use this annotation on methods that should be invoked to handle an exception. The @ExceptionHandler values can be set to an array of Exception types. If an exception is thrown that matches one of the types in the list, then the method annotated with matching @ExceptionHandler will be invoked.

@InitBinder

This annotation is a method level annotation that plays the role of identifying the methods which initialize the WebDataBinder - a DataBinder that binds the request parameter to JavaBean objects. To customise request parameter data binding , you can use @InitBinder annotated methods within our controller. The methods annotated with @InitBinder all argument types that handler methods support.
The @InitBinder annotated methods will get called for each HTTP request if you don’t specify the value element of this annotation. The value element can be a single or multiple form names or request parameters that the init binder method is applied to.

@Mappings and @Mapping

This annotation is used on fields. The @Mapping annotation is a meta annotation that indicates a web mapping annotation. When mapping different field names, you need to configure the source field to its target field and to do that you have to add the @Mappings annotation. This annotation accepts an array of @Mapping having the source and the target fields.

@MatrixVariable

This annotation is used to annotate request handler method arguments so that Spring can inject the relevant bits of matrix URI. Matrix variables can appear on any segment each separated by a semicolon. If a URL contains matrix variables, the request mapping pattern must represent them with a URI template. The @MatrixVariable annotation ensures that the request is matched with the correct matrix variables of the URI.

@PathVariable

This annotation is used to annotate request handler method arguments. The @RequestMapping annotation can be used to handle dynamic changes in the URI where certain URI value acts as a parameter. You can specify this parameter using a regular expression. The @PathVariable annotation can be used declare this parameter.

@RequestAttribute

This annotation is used to bind the request attribute to a handler method parameter. Spring retrieves the named attributes value to populate the parameter annotated with @RequestAttribute. While the @RequestParam annotation is used bind the parameter values from query string, the @RequestAttribute is used to access the objects which have been populated on the server side.

@RequestBody

This annotation is used to annotate request handler method arguments. The @RequestBody annotation indicates that a method parameter should be bound to the value of the HTTP request body. The HttpMessageConveter is responsible for converting from the HTTP request message to object.

@RequestHeader

This annotation is used to annotate request handler method arguments. The @RequestHeader annotation is used to map controller parameter to request header value. When Spring maps the request, @RequestHeader checks the header with the name specified within the annotation and binds its value to the handler method parameter. This annotation helps you to get the header details within the controller class.

@RequestParam

This annotation is used to annotate request handler method arguments. Sometimes you get the parameters in the request URL, mostly in GET requests. In that case, along with the @RequestMapping annotation you can use the @RequestParam annotation to retrieve the URL parameter and map it to the method argument. The @RequestParam annotation is used to bind request parameters to a method parameter in your controller.

@RequestPart

This annotation is used to annotate request handler method arguments. The @RequestPart annotation can be used instead of @RequestParam to get the content of a specific multipart and bind to the method argument annotated with @RequestPart. This annotation takes into consideration the “Content-Type” header in the multipart(request part).

@ResponseBody

This annotation is used to annotate request handler methods. The @ResponseBody annotation is similar to the @RequestBody annotation. The @ResponseBody annotation indicates that the result type should be written straight in the response body in whatever format you specify like JSON or XML. Spring converts the returned object into a response body by using the HttpMessageConveter.

@ResponseStatus

This annotation is used on methods and exception classes. @ResponseStatus marks a method or exception class with a status code and a reason that must be returned. When the handler method is invoked the status code is set to the HTTP response which overrides the status information provided by any other means. A controller class can also be annotated with @ResponseStatus which is then inherited by all @RequestMapping methods.

@ControllerAdvice

This annotation is applied at the class level. As explained earlier, for each controller you can use @ExceptionHandler on a method that will be called when a given exception occurs. But this handles only those exception that occur within the controller in which it is defined. To overcome this problem you can now use the @ControllerAdvice annotation. This annotation is used to define @ExceptionHandler, @InitBinder and @ModelAttribute methods that apply to all @RequestMapping methods. Thus if you define the @ExceptionHandler annotation on a method in @ControllerAdvice class, it will be applied to all the controllers.

@RestController

This annotation is used at the class level. The @RestController annotation marks the class as a controller where every method returns a domain object instead of a view. By annotating a class with this annotation you no longer need to add @ResponseBody to all the RequestMapping method. It means that you no more use view-resolvers or send html in response. You just send the domain object as HTTP response in the format that is understood by the consumers like JSON.

@RestController  is a convenience annotation which combines @Controller  and @ResponseBody .

@RestControllerAdvice

This annotation is applied on Java classes. @RestControllerAdvice is a convenience annotation which combines  @ControllerAdvice and @ResponseBody. This annotation is used along with the @ExceptionHandler annotation to handle exceptions that occur within the controller.

@SessionAttribute

This annotation is used at method parameter level. The @SessionAttribute annotation is used to bind the method parameter to a session attribute. This annotation provides a convenient access to the existing or permanent session attributes.

@SessionAttributes

This annotation is applied at type level for a specific handler. The @SessionAtrributes annotation is used when you want to add a JavaBean object into a session. This is used when you want to keep the object in session for short lived. @SessionAttributes is used in conjunction with @ModelAttribute.
Consider this example.

The @ModelAttribute name is assigned to the @SessionAttributes as value. The @SessionAttributes has two elements. The value element is the name of the session in the model and the types element is the type of session attributes in the model.

Spring Cloud Annotations

@EnableConfigServer

This annotation is used at the class level. When developing a project with a number of services, you need to have a centralized and straightforward manner to configure and retrieve the configurations about all the services that you are going to develop. One advantage of using a centralized config server is that you don’t need to carry the burden of remembering where each configuration is distributed across multiple and distributed components.

You can use Spring cloud’s @EnableConfigServer annotation to start a config server that the other applications can talk to.

@EnableEurekaServer

This annotation is applied to Java classes. One problem that you may encounter while decomposing your application into microservices is that, it becomes difficult for every service to know the address of every other service it depends on. There comes the discovery service which is responsible for tracking the locations of all other microservices.
Netflix’s Eureka is an implementation of a discovery server and integration is provided by Spring Boot. Spring Boot has made it easy to design a Eureka Server by just annotating the entry class with @EnableEurekaServer.

@EnableDiscoveryClient

This annotation is applied to Java classes. In order to tell any application to register itself with Eureka you just need to add the @EnableDiscoveryClientannotation to the application entry point. The application that’s now registered with Eureka uses the Spring Cloud Discovery Client abstraction to interrogate the registry for its own host and port.

@EnableCircuitBreaker

This annotation is applied on Java classes that can act as the circuit breaker. The circuit breaker pattern can allow a micro service continue working when a related service fails, preventing the failure from cascading. This also gives the failed service a time to recover.

The class annotated with @EnableCircuitBreaker will monitor, open, and close the circuit breaker.

@HystrixCommand

This annotation is used at the method level. Netflix’s Hystrix library provides the implementation of Circuit Breaker pattern. When you apply the circuit breaker to a method, Hystrix watches for the failures of the method. Once failures build up to a threshold, Hystrix opens the circuit so that the subsequent calls also fail. Now Hystrix redirects calls to the method and they are passed to the specified fallback methods.
Hystrix looks for any method annotated with the @HystrixCommand annotation and wraps it into a proxy connected to a circuit breaker so that Hystrix can monitor it.

Consider the following example:

Here @HystrixCommand is applied to the original method bookList(). The @HystrixCommand annotation has newList as the fallback method. So for some reason if Hystrix opens the circuit on bookList(), you will have a placeholder book list ready for the users.

Spring Framework DataAccess Annotations

@Transactional

This annotation is placed before an interface definition, a method on an interface, a class definition, or a public method on a class. The mere presence of @Transactional is not enough to activate the transactional behaviour. The @Transactional is simply a metadata that can be consumed by some runtime infrastructure. This infrastructure uses the metadata to configure the appropriate beans with transactional behaviour.

The annotation further supports configuration like:

  • The Propagation type of the transaction
  • The Isolation level of the transaction
  • A timeout for the operation wrapped by the transaction
  • A read only flag - a hint for the persistence provider that the transaction must be read only
    The rollback rules for the transaction

Cache-Based Annotations

@Cacheable

This annotation is used on methods. The simplest way of enabling the cache behaviour for a method is to annotate it with @Cacheable and parameterize it with the name of the cache where the results would be stored.

In the snippet above , the method getAddress is associated with the cache named addresses. Each time the method is called, the cache is checked to see whether the invocation has been already executed and does not have to be repeated.

@CachePut

This annotation is used on methods. Whenever you need to update the cache without interfering the method execution, you can use the @CachePut annotation. That is, the method will always be executed and the result cached.

Using @CachePut and @Cacheable on the same method is strongly discouraged as the former forces the execution in order to execute a cache update, the latter causes the method execution to be skipped by using the cache.

@CacheEvict

This annotation is used on methods. It is not that you always want to populate the cache with more and more data. Sometimes you may want remove some cache data so that you can populate the cache with some fresh values. In such a case use the @CacheEvict annotation.

Here an additional element allEntries is used along with the cache name to be emptied. It is set to true so that it clears all values and prepares to hold new data.

@CacheConfig

This annotation is a class level annotation. The @CacheConfig annotation helps to streamline some of the cache information at one place. Placing this annotation on a class does not turn on any caching operation. This allows you to store the cache configuration at the class level so that you don’t have declare things multiple times.

Task Execution and Scheduling Annotations

@Scheduled

This annotation is a method level annotation. The @Scheduled annotation is used on methods along with the trigger metadata. A method with @Scheduled should have void return type and should not accept any parameters.

There are different ways of using the @Scheduled annotation:

In this case, the duration between the end of last execution and the start of next execution is fixed. The tasks always wait until the previous one is finished.

In this case, the beginning of the task execution does not wait for the completion of the previous execution.

The task gets executed initially with a delay and then continues with the specified fixed rate.

@Async

This annotation is used on methods to execute each method in a separate thread. The @Async annotation is provided on a method so that the invocation of that method will occur asynchronously. Unlike methods annotated with @Scheduled, the methods annotated with @Asynccan take arguments. They will be invoked in the normal way by callers at runtime rather than by a scheduled task.

@Async can be used with both void return type methods and the methods that return a value. However methods with return value must have a Future typed return values.

Spring Framework Testing Annotations

@BootstrapWith

This annotation is a class level annotation. The @BootstrapWith annotation is used to configure how the Spring TestContext Framework is bootstrapped. This annotation is used as a metadata to create custom composed annotations and reduce the configuration duplication in a test suite.

@ContextConfiguration

This annotation is a class level annotation that defines a metadata used to determine which configuration files to use to the load the ApplicationContext for your test. More specifically @ContextConfiguration declares the annotated classes that will be used to load the context. You can also tell Spring where to locate for the file.
@ContextConfiguration(locations={"example/test-context.xml", loader = Custom ContextLoader.class})

@WebAppConfiguration

This annotation is a class level annotation. The @WebAppConfiguration is used to declare that the ApplicationContext loaded for an integration test should be a WebApplicationContext. This annotation is used to create the web version of the application context. It is important to note that this annotation must be used with the @ContextConfiguration annotation.The default path to the root of the web application is src/main/webapp. You can override it by passing a different path to the <span class="theme:classic lang:default decode:true crayon-inline">@WebAppConfiguration.

@Timed

This annotation is used on methods. The @Timed annotation indicates that the annotated test method must finish its execution at the specified time period(in milliseconds). If the execution exceeds the specified time in the annotation, the test fails.

In this example, the test will fail if it exceeds 10 seconds of execution.

@Repeat

This annotation is used on test methods. If you want to run a test method several times in a row automatically, you can use the @Repeat annotation. The number of times that test method is to be executed is specified in the annotation.

In this example, the test will be executed 10 times.

@Commit

This annotation can be used as both class-level or method-level annotation. After execution of a test method, the transaction of the transactional test method can be committed using the @Commit annotation. This annotation explicitly conveys the intent of the code. When used at the class level, this annotation defines the commit for all test methods within the class. When declared as a method level annotation @Commit specifies the commit for specific test methods overriding the class level commit.

@RollBack

This annotation can be used as both class-level and method-level annotation. The @RollBack annotation indicates whether the transaction of a transactional test method must be rolled back after the test completes its execution. If this true @Rollback(true), the transaction is rolled back. Otherwise, the transaction is committed. @Commit is used instead of @RollBack(false).

When used at the class level, this annotation defines the rollback for all test methods within the class.

When declared as a method level annotation @RollBack specifies the rollback for specific test methods overriding the class level rollback semantics.

@DirtiesContext

This annotation is used as both class-level and method-level annotation. @DirtiesContext indicates that the Spring ApplicationContext has been modified or corrupted in some manner and it should be closed. This will trigger the context reloading before execution of next test. The ApplicationContext is marked as dirty before or after any such annotated method as well as before or after current test class.

The @DirtiesContext annotation supports BEFORE_METHOD, BEFORE_CLASS, and BEFORE_EACH_TEST_METHOD modes for closing the ApplicationContext before a test.

NOTE: Avoid overusing this annotation. It is an expensive operation and if abused, it can really slow down your test suite.

@BeforeTransaction

This annotation is used to annotate void methods in the test class. @BeforeTransaction annotated methods indicate that they should be executed before any transaction starts executing. That means the method annotated with @BeforeTransaction must be executed before any method annotated with @Transactional.

@AfterTransaction

This annotation is used to annotate void methods in the test class. @AfterTransaction annotated methods indicate that they should be executed after a transaction ends for test methods. That means the method annotated with @AfterTransaction must be executed after the method annotated with @Transactional.

@Sql

This annotation can be declared on a test class or test method to run SQL scripts against a database. The @Sql annotation configures the resource path to SQL scripts that should be executed against a given database either before or after an integration test method. When @Sql is used at the method level it will override any @Sql defined in at class level.

@SqlConfig

This annotation is used along with the @Sql annotation. The @SqlConfig annotation defines the metadata that is used to determine how to parse and execute SQL scripts configured via the @Sql annotation. When used at the class-level, this annotation serves as global configuration for all SQL scripts within the test class. But when used directly with the config attribute of @Sql, @SqlConfig serves as a local configuration for SQL scripts declared.

@SqlGroup

This annotation is used on methods. The @SqlGroup annotation is a container annotation that can hold several @Sql annotations. This annotation can declare nested @Sql annotations.
In addition, @SqlGroup is used as a meta-annotation to create custom composed annotations. This annotation can also be used along with repeatable annotations, where @Sql can be declared several times on the same method or class.

@SpringBootTest

This annotation is used to start the Spring context for integration tests. This will bring up the full autoconfigruation context.

@DataJpaTest

The @DataJpaTest  annotation will only provide the autoconfiguration required to test Spring Data JPA using an in-memory database such as H2.

This annotation is used instead of @SpringBootTest

@DataMongoTest

The @DataMongoTest  will provide a minimal autoconfiguration and an embedded MongoDB for running integration tests with Spring Data MongoDB.

@WebMVCTest

The @WebMVCTest will bring up a mock servlet context for testing the MVC layer. Services and components are not loaded into the context. To provide these dependencies for testing, the @MockBean annotation is typically used.

@AutoConfigureMockMVC

The @AutoConfigureMockMVC  annotation works very similar to the @WebMVCTest  annotation, but the full Spring Boot context is started.

@MockBean

Creates and injects a Mockito Mock for the given dependency.

@JsonTest

Will limit the auto configuration of Spring Boot to components relevant to processing JSON.

This annotation will also autoconfigure an instance of JacksonTester or GsonTester.

@TestPropertySource

Class level annotation used to specify property sources for the test class.

 

1
Share
, ,

On of the things I love about the Grails environment is that it comes with a handy bootstrap.groovy file. This will run at startup of the Spring container. I frequently use this to setup expected data, or to create test data for integration / functional tests. It can be a very convenient way to seed a H2 database with startup values.

The Spring Framework itself does not have the concept for a bootstrap file like Grails does. It does however have events that we can subscribe to and functionally accomplish the same thing.

Spring Framework Events

The Spring Framework comes out the of box with a number of events, and you’re able to extend the event functionality for your own purposes.

Spring Core Events

ContextRefreshedEvent

This event is published whenever the Spring Context is started or refreshed.

ContextStartedEvent

This event is published when the Spring Context is started.

ContextStoppedEvent

This event is published when the Spring Context is stopped. In practice you will not use this event very often. It can be handy for doing cleanup work, like closing connections.

ContextClosedEvent

This event is similar to the ContextStoppedEvent, but in this case the Context can not be re-started.

Spring Boot Events

Spring Boot introduces several new events on top of the events available in the core Spring Framework.

ApplicationStartedEvent

This event is published early in the startup of a Spring Application. The Spring Context is running, but may change later in the lifecycle.

ApplicationEnvironmentPreparedEvent

This event is published when the Spring Boot Application is starting up and is first available for inspection and modification.

ApplicationPreparedEvent

This event is published when the Spring Context is fully prepared but not refreshed. At this point the Spring Beans are loaded, configured and ready for use.

ApplicationFailedEvent

This event is published when the Spring Boot Application fails to start. This event is useful for error logging or alerting.

Using Spring Framework Events

Under the scenario we want to do something on startup we have two events we can consider using. Traditionally under Spring Framework, we can use the ContextRefreshedEvent. This event has been around since the beginning of the Spring Framework.

If you’re using Spring Boot, you do have additional events to select from. I often want to use a startup event to seed data for tests, so in this case, I need the database connection to be setup. Reading about the Spring Boot Events, I thought the event I would like to use is ApplicationPreparedEvent. But in testing it out, this was not the case. I ran into some issues with getting the event listeners setup properly in the Spring Boot Context. I found better results using the ContextRefreshedEvent.

ContextRefreshedEvent Listener

Here is an example of a listener. Here, I’m injecting a simple bean to prove I got a message. In practice this bean could be whatever you wanted. You could for example inject a Spring Data Repository into your listener bean.

ContextRefresehedListener.java

EventHolderBean.java

Nothing very special about this bean. I have a event fired property, which I initialize to false. If it is true, I know the bean ‘processed’ and event.

Running the Event Bean in Spring Boot

I can run this bean in a Spring Boot Application. Below is my application class.

ContextRefreshedApplication.java

Output

In the output, you can see my console messages.

Testing the Spring Event Bean

I can also set this up in a JUnit test. This will actually run out side of Spring Boot and in a normal Spring context.

To do this I need to setup a simple Java configuration bean for my test.

ContextRefreshConfig.java

ContextRefresehedListenerTest.java

Here I have a simple JUnit test which brings up the Spring Context, and gets an instance of the Event Holder Bean. I check to make sure the event fired is set to true, proving the bean did in fact get manipulated by the event listener.

Test Output

In the output of the test, I can see the console output of the event listener.

Free Introduction to Spring Tutorial

Are you new to the Spring Framework? Checkout my Free Introduction to Spring Online Tutorial.

Get The Code

I’ve committed the source code for this post to github. It is a Maven project which you can download and build. If you wish to learn more about the Spring Framework, I have a free introduction to Spring tutorial. You can sign up for this tutorial in the section below.

Source Code

The source code for this post is available on github. You can download it here.

1
Share
, ,

Polyglot Programming

Is the practice of programming in multiple programming languages. According to Wikipedia it is –

In computing, a polyglot is a computer program or script written in a valid form of multiple programming languages, which performs the same operations or output independent of the programming language used to compile or interpret it.

In writing the code for a recent blog post on Spring Integration, I thought it would be fun to write some of the code in Groovy. I’ve been writing in Groovy for about 7 years. I’m as fluent in Groovy as I am in Java, so its no problem for me to bounce between the two languages. If you been following my blog, you’ve probably seen me use Spock for my unit tests. Spock is a great tool. A Groovy testing framework for testing Java code.

Many Java developers who are not familiar with Groovy, view it as just a scripting language. Groovy is not just a scripting language. It is an Object Oriented Programming language, just like Java is. Some may argue that Groovy is a pure object oriented language and Java is not because of Java’s support of Primitive Types. Because unlike Java, Groovy does autoboxing of primitive types.

Its also important to understand, Groovy was never intended to be a replacement of Java. It’s written to supplement Java. As such, its very easy to mix and match code. Ultimately both Groovy and Java compile down to JVM byte code, and the compiled code is compatible.

Polyglot Programming in the Spring Framework

The Spring Framework is no stranger to Polyglot programming. The Grails community really spearheaded things with the Groovy language. In version 4 of the Spring Framework, we’re seeing a lot more support of polyglot programming around the Groovy language. But in the various Spring Framework projects we’re seeing more polyglot programming support around the Scala programming language. With Rod Johnson involved with Typesafe, I think it’s a safe bet we will see additional support of Scala in Spring in the future.

Groovy Spring Beans

It is possible to write Spring Beans in Groovy. Your application will compile and run just fine. Whenever programming for Dependency Injection, I recommend developing your code to an interface.

AddressService

When doing polyglot programming, I prefer to write the interface in Java. Now any class, written in Java or Groovy can implement the interface. You probably could write the interface in Groovy and use it in Java just fine, but there are some pitfalls of using Groovy from Java you need to be aware of. For example if you use ‘ def ‘ as a type, Java treats it as a Object  data type. Sometimes the strong typing of Java is not a bad thing. This also seems more appropriate to me when defining the interface to use.

AddressServiceImpl.groovy

You can see my Groovy class simply implements the AddressService  interface. I mark the class with the @Service("addressService")  annotation as I would a normal Java Spring Bean. 

Using a link below, you can checkout the full project. You will see the Groovy class compiles with the Java code and runs in the Spring context like any other Spring Bean.

Conclusion

In enterprise Java / Spring shops, you probably will not see much Polyglot programming. But, the Grails team uses Groovy for Spring Beans all the time. I’ve demonstrated its easy to use Groovy Spring beans outside of the Grails environment. This is not a technology issue to overcome. Culturally, I suspect it may be some time before you see polyglot programming in large scale enterprise applications. But doing polyglot programming like this is something fun to do in blog posts!

Get The Code

I’ve committed the source code for this post to github. It is a Maven project which you can download and build. If you wish to learn more about the Spring Framework, I have a free introduction to Spring tutorial. You can sign up for this tutorial in the section below.

Source Code

The source code for this post is available on github. You can download it here.

0
Share
, ,

One of the things I wish to do on this blog is show you realistic examples of using the Spring Framework in Enterprise Application Development. The Spring Framework is very popular for building large scale applications. When you build a ecommerce website that might have 50,000 users on it at any given time the scope of the application you are building changes. This type of site quickly outgrows the traditional 3 tier architecture (web server / app server / database server). The ‘website’ is no longer a simple war file being deployed to Tomcat. You have a data center, with a small server farm. Load balancers, application clusters, message queuing, ‘cloud computing’, micro services. The Spring Framework was not only built for this type of application environment, it thrives in it.

Environments

When you start developing enterprise class applications, you will need to support multiple deployment environments. You’re no longer going to be testing code on your laptop, then deploying it to the production server. Frequently in the enterprise, as a developer you won’t even have access to the production environment. Companies which need to comply with regulations such as SOX, PCI and/or SAS-70 will have specialized teams which will manage code deployments to their testing (QA/UAT) and production environments. This is known as segregation of duties. A very common business practice. From my personal experience it is more stringent in large financial enterprises than it is in retail organizations. Less so in smaller companies because they simply don’t have the resources to support specialized IT staffs.

More modern development cultures will be performing CI builds and automated deployments. Teams on the bleeding edge of modern software development might even be doing continuous deployments I feel continuous deployment is probably the holy grail of software engineering, but in reality it is as rare as a great white buffalo in the wild. I do hope to see more organizations adopt continuous deployments, but it does take a very disciplined organization to get there.

Each of these environments will have its own configuration needs. As the scope of your application grows, chances are the uniqueness of each environment will grow too. The Spring Framework has some outstanding tools which are used to manage the complexities of modern enterprise application development. First, let’s consider some common challenges in the types of environments you will need to support in a large enterprise application.

Local Development

This is your development environment, running from your laptop. This is an area I often see companies absolutely fail at. Your code should be able to run locally, without the need to connect to other servers in the enterprise. Ideally, you should be able to run the code on a plane at 30,000 without a wi-fi connection.

This means:

  • You cannot use an external database. You’re not going to use the Oracle development database.
  • No interaction with other web services.
  • No JMS (MQ Series, Active MQ, Oracle AQ, etc)
  • Your build artifacts need to be locally cached (hello Maven, Ivy!!)

The Grails team does an outstanding job of supporting a local development environment of of the box. When you run Grails in dev mode, it will automatically create an in memory H2 database. Hibernate is used to generate the database tables based on your domain classes.

Continuous Integration

Continuous Integration servers can be tricky little beasts to configure for because of the different types of testing software they accomodate. You may have a project the produces a JAR file, which only has unit tests which will zip right along. You may have integration tests, like Grails does, which bring up an embedded Tomcat instance an H2 in-memory database. Your tests might even perform functional tests using something like Spock and Geb to interact with the embedded Tomcat instance. Its also not uncommon for CI servers to have automated deployment jobs – to another specialized environment.

Each of these scenarios is likely to drive special configuration needs into your application.

Development

Some companies elect to have a development environment. This is typically a production like server environment that the development team has control over. When you deploy into this environment, you will need to configure the application to interact with servers within that environment.

QA / UAT

QA or “Quality Assurance” and UAT “User Acceptance Testing” are environments for non-developer resources to test the software. In some organizations you may have both QA and UAT, or you might have one or the other. If you have both, chances are the organization has formal QA Engineers which work with the QA Environment, and Business Analysts which work with the UAT environment. These environments are often managed by a configuration management team. Sometimes developers will have access to the environment, but often they will not.

Pre-Production or Stage

Pre-Production or Stage (Staging) is an application environment that works with all the production services and supporting databases. This is an environment that allows the deployment of application code, but limits the access to that code. For a website, you might see a special url or access restricted to specific IPs, or throttled by load balancers.

This environment is not as common, but some organizations use it. Facebook deploys code something along this line.

Production

Production is the environment you end users will utilize. This is the main transactional environment and the one your business partners wish to keep operational at all times.

Summary

You can see each of these environments will have its own unique requirements. You’re going to have different database servers, different database versions, often different database vendors. You’ll have different supporting services. For example in an ecommerce website, you might have a payment gateway. In dev, it might be a mock, in test you might be using a testing gateway supplied by your payments provider, and then a different payment gateway for production.

Spring Framework Multi-Environment Support

The Spring Framework was developed from the ground up to support the challenges of supporting complex enterprise environments. You have a number of mature features in the Spring Framework to use in supporting the challenges of enterprise class applications.

Properties

The Spring Framework has excellent support of externalizing properties. “Properties” are simple string values which are externalized from your application. In the Spring Framework properties can be set the following ways:

  • In a traditional properties file. This is typically kept in the resources folder and is often named ‘application.properties’. It is by convention to use <filename>.properties.
  • Using Operating System Environment variables. Java can read values set in the Operating System as environment variables. I’ve used this in the past for things like database settings, which worked out nicely. In this case, my build artifact was easily portable between environments. Once setup, it was effectively ‘drag and drop’ for the support staff.
  • Command line variables. When starting any Java application, you have the opportunity to pass command line variables into the program. This is a handy way to make your build artifact portable. One word of caution, when examining running processes on a system, you can sometimes see the command line information which started the process. So this solution may not be the best option for password strings.

The Spring Framework Support has a number of options for sourcing in property values. One way is using the Spring Expression Language (SpEL). You can see some examples of this in my recent post here.

Dependency Injection

Changing property values is great for things like connecting to a different database server. But often in enterprise class applications you will need behavioral changes which are beyond simple property changes. One of the core features of the Spring Framework is the support of Dependency Injection. Once you become accustomed to development with Dependency Injection with in the Spring Framework, you will see how your code becomes more modular. Your classes will naturally adhere to the Single Responsibility Principle. If you’re doing Dependency Injection against Interfaces, it becomes very easy to swap out components.

Let’s say you have an application which needs to send a JMS message on an event such as a customer purchase. This may trigger an email to the customer about their order, and the data warehouse group might want the purchase information for their analytics. For your unit tests and your integration tests, you might be using Mockito to provide a mock. In your deployed environments you might be using the corporate standard of MQSeries for messaging. But what about doing CI builds? An embedded instance of ActiveMQ just might be perfect solution.

So, in summary, this example has:

  • A Mockito Mock object;
  • 3 different MQ Series configurations;
  • And embedded ActiveMQ.

The MQSeries configurations are easy to handle with property settings. The only thing changing here are the connection parameters. This is the perfect use case for externalized properties.

For your unit tests, if you want to keep them true unit tests (as I defined here), you’ll need to manage the dependency injection yourself. Testing frameworks such as Mocktio and Spock make this easy to do.

If you’re performing integration tests an easy way to manage the Spring Context is through configuration composition. But you may wish to favor using Spring Profiles instead. Each is easy to use, as I explain in the sections below.

Configuration Composition

Inexperienced Spring developers will place all their configuration into single xml files or configuration packages. This is often a mistake since it limits your configuration options. In our example, all of our configuration options could be supported through configuration composition. You would need to place each configuration into a separate xml file, or configuration package. Then selectivity import it into a parent configuration. You basically import the configuration you wish to use into a parent configuration, then load the parent into your Spring Context at run time. This is still a very popular technique to use for testing where it is very easy to specify the Spring context to use at runtime.

For a long time this was the only option Spring developers had to use. In Spring 3.1, Profiles were introduced to help manage different configurations. As you’ll see in the next section this a very powerful feature of Spring.

Spring Framework Profiles

Spring Profiles is a very powerful feature introduced in Spring Framework 3.1. Profiles allow you to define Spring Beans and specify when they should be loaded into the context.

If you do not mark your Spring Been with a profile, it will always be loaded into the Spring Context.

When you do mark your Spring Bean with a profile, then that profile must be set to active for that bean to be loaded into the Spring Context. This makes management of the environment easy, since you can simply mark the different options with the appropriate profile, then when you set that profile option to active, Spring will wire up the appropriate Spring Beans into your application.

There is one special profile that is rather poorly documented, but very nice to use. And that is the default profile. When you mark a Spring Bean using default , this bean is loaded into the context only if no other profile has been set to active. If it there is an active profile, Spring will attempt to find a bean matching that profile first.

What I like about using this option is you don’t have to set an active profile in production. While this is easy to use, from experience it can cause some friction and confusion with the configuration management team. Through the use of default profiles, your application can be deployed into production without an active profile being set.

Going back to the example we’ve been using, I would probably use a CI build profile for the CI build where I wanted to use an embedded instance of ActiveMQ, then setup the MQSeries option using the default profile. Having control over the CI build environment it’s easy for me to specify an active profile, so my CI build profile objects will get loaded into the Spring context. When my example application gets deployed elsewhere, no profile is set to active, so the default profile objects with the MQSeries configuration get loaded into the Spring Context. While we are supporting 3 different environments with MQSeries, this can be managed (and should be) with properties. This is because the MQSeries objects remain the same, except for the configuration of the environment the application is connecting to.

Conclusion

As an application developer, the Spring Framework offers you a lot of options on how you can compose your application. If you’re used to smaller scale development, the plethora of configuration options in the Spring Framework will probably seem like overkill to you. Why would you need such flexibility? Right? No, Wrong. As I’ve shown here, when developing applications in the enterprise you are going to be challenged with supporting the needs of many different environments. You are not just developing code on your laptop. No longer is the production environment the only environment you need to be concerned with. In a large enterprise you will need to support multiple environments, with different configurations and different needs. The Spring Framework has evolved over the years to support the challenging needs of enterprise application development. It’s no wonder that the Spring Framework is the most popular framework to use for developing enterprise class Java applications.

0
Share

Introduction

Spring 3 introduced the Spring Expression Language (SpEL) which has a syntax similar to Unified EL. It can save you a lot of coding, because you can dynamically assign values at runtime.

The folks at Spring, made the Spring Expression Language part of what is considered ‘Spring Core’. Thus, the Spring Expression Language is available for use throughout the Spring Framework.

Spring Framework Overview

SpEL can be configured through files and bean classes using XML and respectively Java annotation.

Spring Expression Language Examples

Project Setup

In this introductory course we will demonstrate how to use SpEL with XML and annotation based configuration to implement a simple example.

The @Component  annotation is used to register the component in Spring. Here are two components annotated correspondingly :

 

We run the application using the App class.

In the first step:
ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
we create an application context using ClassPathXmlApplicationContext which loads the configuration from bean file which is located in class path of the application.
Subsequent steps load the beans (in our case Employee and Company) from the context.
In the end: context.close() the ConfigurableApplicationContext.close() will close the application context, releasing all resources and also destroying all cached singleton beans.

where applicationContext.xml content is:

The applicationContext.xml can enable the auto component-scan to avoid bean declaration in XML file:

Once we created source and bean configuration files, let us run the application. The output will be:

Employee James Smith in Acme Company company and department Information Technology

Project Dependencies:

For a Maven project the pom.xml file is:

Annotation-based configuration

The @Value  annotation allows to specify a default value by placing it on fields, methods and method/constructor parameters. College.java:

Student.java:

after we add in App class the lines:

and run again we will get as result:

Student James Smith from Eastern Florida State College with a Computer Science major

What is actually happening :

1.Beans definitions are loaded
This means scanning the application context XML files, the packages defined by component-scan, and loading the bean definitions found into the bean factory.

2.The beans are instantiated and stored in the application context
The bean factory creates each bean from the bean definitions, while the bean dependencies get injected.

3.The beans are post processed
All initializing methods declared in the XML method will be executed, while Annotations will be validated.

XML Based Configuration

Literal Values

We used literal values to bean properties:

Any data type can be used.

Bean Reference

we can refer other spring beans using SpEL:

which can be also written:

The outcome from both the above expressions is same.

Property references

We can use literal values to bean properties using SpEL:

for a nested property value a period (.) is used

for which is the same as:

Method references

are the way a method references another bean:

on which we can use operator for example:

To avoid a NullPointerExeception we should use the Safe Navigation Operator “?.”:

SpEL Predefined Variables

In SpEL “systemProperties” and “systemEnvironment“ are part of a Environment bean which provide information at runtime (late binding):

systemProperties that contains the environment variables on the machine where the application is running.
systemEnvironment – that is retrieving environment specific properties from the runtime environment, more specifically Java properties that we set in Java when the application started (using the -D argument)

Let’s first define an environment variable appHome with the value: C:/somePath and see how to make it available through SpEL.

After we autowire the Environment object in the current Spring container and we use the injected parameter by @Value  in an instance variable of the class we have the environment variable we looking for.

Running it:

will give the same result: environment variable value appHome = C:/somePath as:

where in the configuration.properties file (under resources directory) we have defined: appHome=C:/somepath

In this example we used @PropertySource  annotations to read properties file, annotation placed on core Spring configuration classes ( @Configuration ).

Conclusion

The Spring Expression Language is a powerful feature of a the Spring Framework. As you develop enterprise class applications in Spring, you will frequently encounter uses for the Spring Expression Language. A very common use for the Spring Expression Language is in defining your database settings. In a typical enterprise, you will have a development environment, a QA or testing environment, and your production deployment environment. The database server and settings will be different for each of these environments. The Spring Expression Language makes it easy to externalize your database properties.

Get the code!

Source Code

The source code for this post is available on github. You can download it here.

0
Share
,

There are several ways of defining Spring Beans in the Spring Framework. Each method has its own advantages and disadvantages. You may be wondering which one should you use. The answer is, it depends. The reality is in a large enterprise Spring project, you will likely encounter a combination of methods in defining Spring Beans. Neither is wrong, nor necessarily better. In legacy Spring applications, you’re likely to encounter XML based Spring Configuration. In new Spring applications, you’re likely to encounter more annotation based configurations and Java based configurations.

In this post, I’ll step you through common ways of defining Spring Beans. At the end of the post, I’ll show you how the different methods work seamlessly.

Say Hello Spring Bean

All the examples in this post will implement the following Interface. We will use simple Hello World type beans which will print a message to the system console.

Spring Configuration

XML Based Configuration

XML based Spring Configuration has been around since the beginning of Spring. It is the oldest and most mature method of defining Spring Beans.

Hello Spring Bean

Here is the Spring Bean we will use for this example.

Spring XML Configuration

Application

The following code can be used to execute the example Spring Bean.

Output

Java Based Configuration

In Spring 3, Java based configuration was released. The Spring community is gradually converting over to prefer the use of Java based configuration over XML based configuration. It is somewhat easier to use than XML. Since the configuration is in Java, you do have a tremendous amount of flexibility in defining beans. You’re no longer bound by the constraints of describing beans in XML, and have the full power of the Java language at your disposal.

Hello Spring Bean

Java Configuration Class

The following class is a Spring Configuration class. The annotation @Configuration  at the top of the class defines the class as a configuration class. The class will be picked up in a Spring component scan. It can also be imported into other configuration classes too. Objects returned  @Bean  annotation will be registered as Spring Beans. By convention the name of the registered Spring Bean will be set equal to the name of the method.  

Application

The following code can be used to execute the example Spring Bean.

Output

Annotation Based Configuration

Spring also can detect beans based on class level annotations. Any class annotated with with @Component , @Service , @Controller , or @Repository  will be considered a Spring Bean. The class must reside in a package which had been identified for a component scan. Spring will scan the package for annotated classes. Any class detected will be managed by the Spring Context at run time.

Hello Spring Bean

Application

The following code can be used to execute the example Spring Bean.

Output

Using Spring Bean Configurations Together

While there are different ways of defining Spring Beans, its important to remember the different methods can be used together. Its very common to use multiple methods of defining Spring Beans in a single application.

Spring Bean Application

We can use the beans previously defined to demonstrate how this works seamlessly. The Spring component scan functionality will detect classes annotated as Spring Beans, and classes marked as configuration classes which also define Spring Beans. In the following code example, the annotation @ComponentScan("guru.springframework") tells Spring to perform a component scan on the package guru.springframework.

This technique will work for annotated classes, but it not pick up XML configuration files. The annotation @ImportResource("classpath*:spring/spring-config.xml") will bring the specified xml file into the Spring context.

The class below is annotated to perform the component scan, which will pick up Spring Beans defined in Java configuration classes, Spring Beans defined with annotations, and Spring Beans defined in XML configuration files.

Output

When you run the above class, you will see the following output.

Get The Code

I’ve committed the source code for this post to github. It is a Maven project which you can download and build. If you wish to learn more about the Spring Framework, I have a free introduction to Spring tutorial. You can sign up for this tutorial in the section below.

Source Code

The source code for this post is available on github. You can download it here.

Video Code Review

I’ve posted a code review of this post on YouTube. In the review I step through the classes we used in this post.

2
Share
,

Dependency Injection

The Spring Framework is literally built around the concept of Dependency Injection. In this post, we’ll take a look at a simple example of Dependency Injection using the Spring Framework.

If you want a deeper dive on Dependency Injection and how it works in conjunction with Inversion of Control in the Spring Framework, sign up for my free Introduction to Spring tutorial at the bottom of this post.

Dependency Injection Example

In this blog post, I will take a realistic example of having a web controller and a service. In practice, the controller would be responsible for managing requests from the web, and the service would interact with the persistence layer.

Domain

Our service will return a domain class. In this example, our controller will return a simple list of products.

Product Class

Service Layer

Ideally, when you are coding for Dependency Injection, you will want to code to an interface. This will allow you easily utilize polymorphism and implement different concrete implementations. When coding for the use of dependency injection, coding to an interface also complies with the Interface Segregation Principle of the SOLID principles of Object Oriented Programming.

A common example would be to have the implementation you will use in your production code, and then a mock implementation for unit testing your code. This is the power of dependency injection. It allows you to change the behavior of your application through configuration changes over code changes. For example with persistence, you might be injecting a mock for unit testing, a H2 database for local development and CI builds, and then a Oracle implementation when your code is running in production. When developing enterprise class applications, dependency injection gives you a tremendous amount of versatility. 

Interface

Example Interface:

Implementation

Here is the implementation of the service. This is just a simple implementation which returns a list of Product domain POJOs, which is sufficient for this example. Naturally, in a real example, this implementation would be interacting with the database or possibly a web service.

I’ve annotated the class with @Service , this tells Spring this class is a Spring Bean to be managed by the Spring Framework. This step is critical, Spring will not detect this class as a Spring Bean without this annotation. Alternatively, you could explicitly define the bean in a Spring configuration file.

Controller

We have a simple controller to return a list of Products to our view layer. In this example, I’m using setter based Dependency Injection.   First, I’ve defined a property in our example controller using the Interface type, not the concrete class. This allows any class to be injected which implements the specified interface.  On the setter, you see the @Autowired  annotation. This directs Spring to inject a Spring managed bean into this class.  Our controller class is also annotated with the @Controller  annotation. This marks the class as a Spring Managed bean. Without this annotation, Spring will not bring this class into the context, and will not inject an instance of the service into the class.  

Running the Example

We’ll use Spring Boot to run our example. Spring Boot will help bring up the Spring context for running our example. Spring Boot does automate a lot of common tasks for us. For example, it will automatically do a component scan in the package the class is running in.

Example Execution Code

For our example, we need to tell Spring where our components are located. We use the @ComponentScan  annotation. By using this annotation Spring will scan the specified package for Spring components (aka Spring managed beans).

In our main method, we get the Spring Context, then request from the context an instance of our controller bean. Spring will give us an instance of the controller. Spring will perform the Dependency Injection for us, and inject the dependent components into the object returned to us.

It is important to remember, the Spring Context is returning to us Spring Managed beans. This means Spring will be managing the dependency injection for us. If for some reason, Spring cannot fulfill a dependency, it will fail to startup. You will see in the stack trace information about the missing dependencies.

Console Output

When you run the above example, you will see the following output in the console.  Note in the console output, you see our two product descriptions, which proves that Spring did in fact wire our controller correctly. If Spring did not, our code would have failed on a null pointer error.  

Video Code Review

Below is a brief video where I review the code used in this example.

Conclusion

In this post we demonstrated a very basic example of Spring Dependency Injection using the Spring Framework. I hope you can see how simple Spring makes Dependency Injection. If you wish to learn more about the Spring Framework and Dependency Injection, checkout my free Introduction to Spring Tutorial!

Free Introduction to Spring Tutorial

Are you new to the Spring Framework? Checkout my Free Introduction to Spring Online Tutorial.

 

Get The Code

A complete working example of the code for this post is available on github.

The source code for this post is available on github. You can download it here.

4
Share
, ,

This is a simple hello world example using Spring Framework 4. We will use Spring Boot and Spring Initializer to get things kicked off easily.

Video Tutorial

Follow this quick video tutorial to get a Spring Boot starter project.

Step by Step Instructions

Get Starter Project from Spring Initializer

Step One

  • Go to the Spring Initializer website via this link.
  • For our hello world example, all the defaults are fine.
  • Click the Generate Button.

Generate Project Button

This will download a zip file containing a starter project to your hard drive.

Import Project Into IntelliJ

Step Two

Unzip the contents of the downloaded file to a working directory.

You now have a basic Spring project using Maven. The downloaded file contains the default Maven project structure. At the root of the directory is a pre-configured POM that contains a Spring Boot dependency. The Spring Boot dependency has child dependencies for Spring Core modules.

Step Three

Import project into your IDE. Our favorite IDE is IntelliJ.

  • From IntelliJ go to File / New / Project from Existing Sources.
  • Locate the file pom.xml in the root folder of the downloaded project and click OK.
  • Click next from the Import from Maven screen.

Import Project from Maven

  • Select Maven Project, Click Next.

Import Project from Maven

 

  • Select the SDK to use. (You should select Java 1.8 or higher)

Import Project from Maven

 

  • Select name for the project. (Demo is fine for this)

Import project from Maven

  • At this point the Maven project has been imported into the IntelliJ IDE.

IntelliJ

Newsletter

Join the Spring Guru Newsletter!

Stay updated on the latest and greatest happening at springframework.guru.

[mc4wp_form]

Update Code

Step Four

Create a HelloWorld class which will print ‘Hello World’ to the console in Java.

Step Five

Update the main method to get an instance of the HelloWorld bean from the Spring Context.

Run Project – Say Hello

Step Six

Run the main method.

. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v1.2.2.RELEASE)
2015-03-11 10:25:18.981 INFO 7394 --- [ main] demo.DemoApplication : Starting DemoApplication on Johns-MacBook-Pro.local with PID 7394 (/Users/jt/src/springframework.guru/blog/hello-world-spring-4/demo/target/classes started by jt in /Users/jt/src/springframework.guru/blog/hello-world-spring-4/demo)
2015-03-11 10:25:19.050 INFO 7394 --- [ main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.spring[email protected]3e57cd70: startup date [Wed Mar 11 10:25:19 EDT 2015]; root of context hierarchy
2015-03-11 10:25:20.143 INFO 7394 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2015-03-11 10:25:20.159 INFO 7394 --- [ main] demo.DemoApplication : Started DemoApplication in 1.517 seconds (JVM running for 2.092)
Hello World
2015-03-11 10:25:20.162 INFO 7394 --- [ Thread-1] s.c.a.AnnotationConfigApplicationContext : Closing org.spring[email protected]3e57cd70: startup date [Wed Mar 11 10:25:19 EDT 2015]; root of context hierarchy
2015-03-11 10:25:20.164 INFO 7394 --- [ Thread-1] o.s.j.e.a.AnnotationMBeanExporter : Unregistering JMX-exposed beans on shutdown
Process finished with exit code 0

Get The Code

Source Code

The source code for this post is available on github. You can download it here.

Want to Learn More About Spring?

Free Spring Framework Tutorial

Are you new to the Spring Framework? Checkout my completely free online tutorial for the Spring Framework!

spring-framework-project-logo

Get Access the Spring Framework Guru’s free Introduction to Spring Tutorial!

The first module of the Spring Framework Guru’s free Introduction to the Spring Framework tutorial is ready. Get access to the tutorial by clicking the link below.

0
Share
, ,

Today I released the first module of my Introduction to Spring Framework Tutorial. I hope you enjoy it.

Seems like I see two types of tutorials on the web now. One is the very long blog post. The other is the 45 minute video tutorial. The problem with either format that we can only hold our attention for a limited time. For a video, 20 minutes if you’re lucky. I’ve divided my tutorial in to multiple units, which vary in length. Some units are more of a blog post, some are just a quiz, some include a short video. By mixing up the media and what you are doing, I hope you will avoid zoning out and retain the information better. Feedback is always welcome!

My Spring Framework Tutorial starts with some of the core concepts behind the Spring Framework, then shows some examples of using Spring in a realistic situation.

I still have additional modules to complete. But I wanted to get this published so people could access it.

Enjoy! John

spring-framework-project-logo

Get Access the Spring Framework Guru’s free Introduction to Spring Tutorial!

The first module of the Spring Framework Guru’s free Introduction to the Spring Framework tutorial is ready. Get access to the tutorial by clicking the link below.

0
Share