Difference between Setter vs Constructor Injection in Spring

Spring Setter vs Constructor Injection

Spring supports two types of dependency Injection, using setter method e.g. setXXX() where XXX is a dependency or via a constructor argument. The first way of dependency injection is known as setter injection while later is known as constructor injection. Both approaches of Injecting dependency on Spring bean has there pros and cons, which we will see in this Spring framework article. The difference between Setter Injection and Constructor Injection in Spring is also a popular Spring framework interview question.Some time interviewer also asks as When do you use Setter Injection over Constructor injection in Spring or simply benefits of using setter vs constructor injection in Spring framework. Points discussed in this article not only help you to understand Setter vs Constructor Injection but also Spring’s dependency Injection process.

By the way, if you are new in Spring framework and learning it, you may want to take a look at my list of 5 good books to learn Spring framework. That will certainly help in  your learning process. Since Spring is now a must have skill for Java programmers, it worth putting time and effort to learn this powerful framework

Difference between Setter and Constructor Injection in Spring framework

As I said earlier Spring supports both setter and constructor Injection which are two standard way of injecting dependency on beans managed by IOC constructor. Spring framework doesn’t support Interface Injection on which dependency is injected by implementing a particular interface. In this section we will see a couple of difference between setter and constructor Injection, which will help you decide when to use setter Injection over constructor Injection in Spring and vice-versa.

1) The fundamental difference between setter and constructor injection, as their name implies is How dependency is injected.  Setter injection in Spring uses setter methods like setDependency() to inject dependency on any bean managed by Spring’s IOC container. On the other hand constructor injection uses constructor to inject dependency on any Spring-managed bean.
2) Because of using setter method, setter Injection in more readable than constructor injection in Spring configuration file usually applicationContext.xml . Since setter method has name e.g. setReporotService() by reading Spring XML config file you know which dependency you are setting. While in constructor injection, since it uses an index to inject the dependency, it’s not as readable as setter injection and you need to refer either Java documentation or code to find which index corresponds to which property.
3) Another difference between setter vs constructor injection in Spring and one of the drawback of  setter injection is that it does not ensures dependency Injection. You can not guarantee that certain dependency is injected or not, which means you may have an object with incomplete dependency. On other hand constructor Injection does not allow you to construct object, until your dependencies are ready.
4) One more drawback of setter Injection is Security. By using setter injection, you can override certain dependency which is not possible which is not possible with constructor injection because every time you call the constructor, a new object is gets created.

5) One of our reader Murali Mohan Reddy pointed out one more difference between Setter and Constructor injection in Spring, where later can help if there is a circular dependency between two object A and B.
If Object A and B are dependent each other i.e A is depends ob B and vice-versa. Spring throws ObjectCurrentlyInCreationException while creating objects of A and B bcz A object cannot be created until B is created and vice-versa. So spring can resolve circular dependencies through setter-injection. Objects constructed before setter methods invoked.
See comment section for more inputs from other readers.

When to use Setter Injection over Constructor Injection in Spring

Setter Injection has upper hand over Constructor Injection in terms of readability. Since for configuring Spring we use XML files, readability is much bigger concern. Also drawback of setter Injection around ensuring mandatory dependency injected or not can be handled by configuring Spring to check dependency using “dependency-check” attribute of  tag or tag. Another worth noting point to remember while comparing Setter Injection vs Constructor Injection is that, once number of dependency crossed a threshold e.g. 5 or 6 its handy manageable to passing dependency via constructor. Setter Injection is preferred choice when number of dependency to be injected is lot more than normal, if some of those arguments is optional than using Builder design pattern is also a good option.
In Summary, both Setter Injection and Constructor Injection has there own advantage and disadvantage. The good thing about Spring is that it doesn’t restrict you to use either Setter Injection or Constructor Injection and you are free to use both of them in one Spring configuration file. Use Setter injection when a number of dependencies are more or you need readability. Use Constructor Injection when Object must be created with all of its dependency.

 

Spring Security Example Tutorial – How to limit number of User Session in Java

Spring security can limit number of session a user can have. If you are developing web application specially secure web application in Java J2EE then you must have come up with requirement similar to online banking portals have e.g. only one session per user at a time or no concurrent session per user. You can also implement this functionality without using spring security but with Spring security its just piece of cake with coffee :). Spring Security provides lots of Out of Box functionality a secure enterprise or web application needed like authentication, authorization, session management, password encoding, secure access, session timeout etc. In our spring security example we have seen how to do LDAP Authentication in Active directory using spring security and in this spring security example we will see how to limit number of session user can have in Java web application or restricting concurrent user session.

Spring Security Example: Limit Number of User Session

As I said it’s simple and easy when you use spring security framework or library. In fact is all declarative and no code is require to enable concurrent session disable functionality. You will need to include following xml snippet in your Spring Security Configuration file mostly named as applicaContext-security.xml. Here is sample spring security Example of limiting user session in Java web application:

<session-management invalid-session-url="/logout.html">
    <concurrency-control max-sessions="1" error-if-maximum-exceeded="true" />
</session-management>

As you see you can specify how many concurrent session per user is allowed, most secure system like online banking portals allow just one authenticate session per user. You can even specify a URL where user will be taken if they submit an invalid session identifier can be used to detect session timeout. Session-management element is used to capture session related stuff. Max-session specify how many concurrent authenticated session is allowed and if error-if-maximum-exceeded set to true it will flag error if user tries to login into another session.

Dependency

This code has dependency on spring-security framework. You need to download spring security jar like spring-security-web-3.1.0.jar and add into application classpath.

This simple example of spring security shows power of spring security, a small piece of xml snippet can add very useful and handy security feature in your Java web application. I recommend using spring security for your new or existing Java web application created using Servlet JSP.

That’s all on how to limit number of user session using spring security in Java web application. Let me know if you face any issue while implementing this security feature in your project.

 

An Intro to the Spring DispatcherServlet!

1. Introduction

Simply put, in the Front Controller design pattern, a single controller is responsible for directing incomingHttpRequests to all of an application’s other controllers and handlers.

Spring’s DispatcherServlet implements this pattern and is, therefore, responsible for correctly coordinating the HttpRequests to their right handlers.

In this article, we will examine the Spring DispatcherServlet’s request processing workflow and how to implement several of the interfaces that participate in this workflow.

2. DispatcherServlet Request Processing

Essentially, a DispatcherServlet handles an incoming HttpRequest, delegates the request, and processes that request according to the configured HandlerAdapter interfaces that have been implemented within the Spring application along with accompanying annotations specifying handlers, controller endpoints, and response objects.

Let’s get more in depth about how a DispatcherServlet processes a component:

  • the WebApplicationContext associated to a DispatcherServlet under the key DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE is searched for and made available to all of the elements of the process
  • The DispatcherServlet finds all implementations of the HandlerAdapter interface configured for your dispatcher using getHandler() – each found and configured implementation handles the request via handle()  through the remainder of the process
  • the LocaleResolver is optionally bound to the request to enable elements in the process to resolve the locale
  • the ThemeResolver is optionally bound to the request to let elements, such as views, determine which theme to use
  • if a MultipartResolver is specified, the request is inspected for MultipartFiles – any found are wrapped in a MultipartHttpServletRequest for further processing
  • HandlerExceptionResolver implementations declared in the WebApplicationContext pick up exceptions that are thrown during processing of the request

You can learn more about all the ways to register and set up a DispatcherServlet here.

3. HandlerAdapter Interfaces

The HandlerAdapter interface facilitates the use of controllers, servlets, HttpRequests, and HTTP paths through several specific interfaces. The HandlerAdapter interface thus plays an essential role through the many stages of the DispatcherServlet request processing workflow.

First, each HandlerAdapter implementation is placed into the HandlerExecutionChain from your dispatcher’s getHandler() method. Then, each of those implementations handle() the HttpServletRequest object as the execution chain proceeds.

In the following sections, we will explore a few of the most important and commonly used HandlerAdapters in greater detail.

3.1. Mappings

To understand mappings, we need to first look at how to annotate controllers since controllers are so essential to the HandlerMapping interface.

The SimpleControllerHandlerAdapter allows for the implementation of a controller explicitly without a @Controller annotation.

The RequestMappingHandlerAdapter supports methods annotated with the @RequestMapping annotation.

We’ll focus on the @Controller annotation here, but a helpful resource with several examples using the SimpleControllerHandlerAdapter is also available.

The @RequestMapping annotation sets the specific endpoint at which a handler will be available within the WebApplicationContext associated with it.

Let’s see an example of a Controller that exposes and handles the ‘/user/example’ endpoint:

1
2
3
4
5
6
7
8
9
10
@Controller
@RequestMapping("/user")
@ResponseBody
public class UserController {
 
    @GetMapping("/example")
    public User fetchUserExample() {
        // ...
    }
}

The paths specified by the @RequestMapping annotation are managed internally via the HandlerMapping interface.

The URLs structure is naturally relative to the DispatcherServlet itself – and determined by the servlet mapping.

Thus, if the DispatcherServlet is mapped to ‘/’, then all mappings are going to be covered by that mapping.

If, however, the servlet mapping is ‘/dispatcher‘ instead, then any @RequestMapping annotations are going to be relative to that root URL.

Remember that ‘/’ is not the same as ‘/*’ for servlet mappings! ‘/’ is the default mapping and exposes all URL’s to the dispatcher’s area of responsibility.

‘/*’  is confusing to a lot of newer Spring developers. It does not specify that all paths with the same URL context are under the dispatcher’s area of responsibility. Instead, it overrides and ignores the other dispatcher mappings. So, ‘/example’ will come up as a 404!

For that reason, ‘/*’ shouldn’t be used except in very limited circumstances (like configuring a filter).

3.2. HTTP Request Handling

The core responsibility of a DispatcherServlet is to dispatch incoming HttpRequests to the correct handlersspecified with the @Controller or @RestController annotations.

As a sidenote, the main difference between @Controller and @RestController is how the response is generated – the @RestController also defines @ResponseBody by default.

A writeup where we go into much greater depth regarding Spring’s controllers can be found here.

3.3. The ViewResolver Interface

A ViewResolver is attached to a DispatcherServlet as a configuration setting on an ApplicationContext object.

A ViewResolver determines both what kind of views are served by the dispatcher and from where they are served.

Here’s an example configuration which we’ll place into our WebMvcConfigurerAdapter for rendering JSP pages:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@Configuration
@EnableWebMvc
@ComponentScan("com.baeldung.springdispatcherservlet")
public class AppConfig extends WebMvcConfigurerAdapter {
    @Bean
    public UrlBasedViewResolver viewResolver() {
        UrlBasedViewResolver resolver
          = new UrlBasedViewResolver();
        resolver.setPrefix("/WEB-INF/jsp/");
        resolver.setSuffix(".jsp");
        resolver.setViewClass(JstlView.class);
        return resolver;
    }
}

Very straight-forward! There are three main parts to this:

  1. setting the prefix, which sets the default URL path to find the set views within
  2. the default view type which is set via the suffix
  3. setting a view class on the resolver which allows technologies like JSTL or Tiles to be associated with the rendered views

One common question involves how precisely a dispatcher’s ViewResolver and the overall project directory structure are related. Let’s take a look at the basics.

Here’s an example path configuration for an InternalViewResolver using Spring’s XML configuration:

1
<property name="prefix" value="/jsp/"/>

For the sake of our example, we’ll assume that our application is being hosted on:

This is the default address and port for a locally hosted Apache Tomcat server.

Assuming that our application is called dispatcherexample-1.0.0, our JSP views will be accessible from:

The path for these views within an ordinary Spring project with Maven is this:

1
2
3
4
5
6
7
src -|
     main -|
            java
            resources
            webapp -|
                    jsp
                    WEB-INF

The default location for views is within WEB-INF. The path specified for our InternalViewResolver in the snippet above determines the subdirectory of ‘src/main/webapp’ in which your views will be available.

 3.4. The LocaleResolver Interface

The primary way to customize session, request, or cookie information for our dispatcher is through theLocaleResolver interface.

CookieLocaleResolver is an implementation allowing the configuration of stateless application properties using cookies. Let’s add it to AppConfig.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@Bean
public CookieLocaleResolver cookieLocaleResolverExample() {
    CookieLocaleResolver localeResolver
      = new CookieLocaleResolver();
    localeResolver.setDefaultLocale(Locale.ENGLISH);
    localeResolver.setCookieName("locale-cookie-resolver-example");
    localeResolver.setCookieMaxAge(3600);
    return localeResolver;
}
@Bean
public LocaleResolver sessionLocaleResolver() {
    SessionLocaleResolver localeResolver = new SessionLocaleResolver();
    localeResolver.setDefaultLocale(Locale.US);
    localResolver.setDefaultTimeZone(TimeZone.getTimeZone("UTC"));
    return localeResolver;
}

SessionLocaleResolver allows for session-specific configuration in a stateful application.

The setDefaultLocale() method represents a geographical, political, or cultural region, whereas setDefaultTimeZone() determines the relevant TimeZone object for the application Bean in question.

Both methods are available on each of the above implementations of LocaleResolver.

3.5. The ThemeResolver Interface

Spring provides stylistic theming for our views.

Let’s take a look at how to configure our dispatcher to handle themes.

First, let’s set up all the configuration necessary to find and use our static theme files. We need to set a static resource location for our ThemeSource to configure the actual Themes themselves (Theme objects contain all of the configuration information stipulated in those files). Add this to AppConfig:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/resources/**")
      .addResourceLocations("/", "/resources/")
      .setCachePeriod(3600)
      .resourceChain(true)
      .addResolver(new PathResourceResolver());
}
@Bean
public ResourceBundleThemeSource themeSource() {
    ResourceBundleThemeSource themeSource
      = new ResourceBundleThemeSource();
    themeSource.setDefaultEncoding("UTF-8");
    themeSource.setBasenamePrefix("themes.");
    return themeSource;
}

Requests managed by the DispatcherServlet can modify the theme through a specified parameter passed into setParamName() available on the ThemeChangeInterceptor object. Add to AppConfig:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
@Bean
public CookieThemeResolver themeResolver() {
    CookieThemeResolver resolver = new CookieThemeResolver();
    resolver.setDefaultThemeName("example");
    resolver.setCookieName("example-theme-cookie");
    return resolver;
}
@Bean
public ThemeChangeInterceptor themeChangeInterceptor() {
   ThemeChangeInterceptor interceptor
     = new ThemeChangeInterceptor();
   interceptor.setParamName("theme");
   return interceptor;
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(themeChangeInterceptor());
}

The following JSP tag is added to our view to make the correct styling appear:

1
<link rel="stylesheet" href="${ctx}/<spring:theme code='styleSheet'/>" type="text/css"/>

The following URL request renders the example theme using the ‘theme’ parameter passed into our configured ThemeChangeIntercepter:

3.6. The MultipartResolver Interface

A MultipartResolver implementation inspects a request for multiparts and wraps them in a MultipartHttpServletRequest for further processing by other elements in the process if at least one multipart is found. Add to AppConfig:

1
2
3
4
5
6
7
8
@Bean
public CommonsMultipartResolver multipartResolver()
  throws IOException {
    CommonsMultipartResolver resolver
      = new CommonsMultipartResolver();
    resolver.setMaxUploadSize(10000000);
    return resolver;
}

Now that we’ve configured our MultipartResolver bean, let’s set up a controller to process MultipartFile requests:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
@Controller
public class MultipartController {
    @Autowired
    ServletContext context;
    @PostMapping("/upload")
    public ModelAndView FileuploadController(
      @RequestParam("file") MultipartFile file)
      throws IOException {
        ModelAndView modelAndView = new ModelAndView("index");
        InputStream in = file.getInputStream();
        String path = new File(".").getAbsolutePath();
        FileOutputStream f = new FileOutputStream(
          path.substring(0, path.length()-1)
          + "/uploads/" + file.getOriginalFilename());
        int ch;
        while ((ch = in.read()) != -1) {
            f.write(ch);
        }
        f.flush();
        f.close();
        modelAndView.getModel()
          .put("message", "File uploaded successfully!");
        return modelAndView;
    }
}

We can use a normal form to submit a file to the specified endpoint. Uploaded files will be available in ‘CATALINA_HOME/bin/uploads’.

3.7. The HandlerExceptionResolver Interface

Spring’s HandlerExceptionResolver provides uniform error handling for an entire web application, a single controller, or a set of controllers.

To provide application-wide custom exception handling, create a class annotated with @ControllerAdvice:

1
2
3
4
5
6
7
8
9
@ControllerAdvice
public class ExampleGlobalExceptionHandler {
    @ExceptionHandler
    @ResponseBody
    public String handleExampleException(Exception e) {
        // ...
    }
}

Any methods within that class annotated with @ExceptionHandler will be available on every controller within dispatcher’s area of responsibility.

Implementations of the HandlerExceptionResolver interface in the DispatcherServlet’s ApplicationContext are available to intercept a specific controller under that dispatcher’s area of responsibility whenever @ExceptionHandler is used as an annotation, and the correct class is passed in as a parameter:

1
2
3
4
5
6
7
8
9
@Controller
public class FooController{
    @ExceptionHandler({ CustomException1.class, CustomException2.class })
    public void handleException() {
        // ...
    }
    // ...
}

The handleException() method will now serve as an exception handler for FooController in our example above if either exception CustomException1 or CustomException2 occurs.

Here’s an article that goes more in depth about exception handling in a Spring web application.

 4. Conclusion

In this tutorial, we’ve reviewed Spring’s DispatcherServlet and several ways to configure it.

As always, the source code used in this tutorial is available over on Github.

Spring Transaction Management Over Multiple Threads

Image title

The Spring framework provides a comprehensive API for database transaction management. Spring takes care of all underlying transaction management considerations and provides a consistent programming model for different transaction APIs such as Java Transaction API (JTA), JDBC, Hibernate, Java Persistence API (JPA), and Java Data Objects (JDO). There are two main types of transaction management in Spring: declarative transaction management, which is a high level one, and programmatic transaction management, which is more advanced but flexible.

The Spring API works very well with almost all of the transaction management requirements as long as the transaction is on a single thread. The problem arises when we want to manage a transaction across multiple threads. Spring doesn’t support transactions over multiple threads out of the box. Spring doesn’t explicitly mention that in the documentation, but you will end up with runtime errors or unexpected results if you try to do so.

Why Do Spring Transactions Over Multiple Threads Fail?

Spring stores a set of thread locals inside the  org.springframework.transaction.support.TransactionSynchronizationManager class. These thread locals are specific for an ongoing transaction on a single thread (Thread locals values are specific for a single thread. Thread local value set by one thread cannot be accessed by another thread).

public abstract class TransactionSynchronizationManager {
private stati final Log logger = LogFactory.getLog(TransactionSynchronizationManager.class);
private static final ThreadLocal<Map<Object, Object>> resources = new NamedThreadLocal("Transactional resources");
private static final ThreadLocal<Set<TransactionSynchronization>> synchronizations = new NamedThreadLocal("Transaction synchronizations");
private static final ThreadLocal<String> currentTransactionName = new NamedThreadLocal("Current transaction name");
private static final ThreadLocal<Boolean> currentTransactionReadOnly = new NamedThreadLocal("Current transaction read-only status");
private static final ThreadLocal<Integer> currentTransactionIsolationLevel = new NamedThreadLocal("Current transaction isolation level");
private static final ThreadLocal<Boolean> actualTransactionActive = new NamedThreadLocal("Actual transaction active");
}

If we start the transaction from one thread and try to commit or rollback the transaction from another thread, a runtime error will be generated complaining that the Spring transaction is not active on the current thread. Though we start and end the transaction from the same thread, we cannot perform database operations belong to transaction from another thread too.

When we initialize the transaction the  actualTransactionActive thread local is set to true.  synchronizations thread local is also initialized. Other thread locals are also accessed and updated during the lifecycle of the transaction. When we try to commit or rollback the transaction at the end of the transaction scope, values of these thread locals are again checked. What happens if we use multiple threads for the transaction is that these thread local values are not visible across multiple threads. Therefore, Spring cannot maintain the transaction state throughout the transaction.

How to Use Spring Transactions With Multiple Threads

Now you understand the problem with spring transactions over multiple threads. The thread local values are not propagating to new threads from old threads. The only solution here is to manually copy these thread local values to newly spawned threads to keep the transaction unbroken.

As mentioned above,  actualTransactionActive thread local is used to check whether the transaction is active on the current thread. This thread local is set true on the thread which initializes the transaction. But, since this thread local value is not visible to other threads, we have to maintain another boolean flag to inform the activeness of the transaction to other threads. Then we can check that flag from the new thread and set  actualTransactionActive thread local to true manually. Thread local value can be set by calling following code line:

TransactionSynchronizationManager.setActualTransactionActive(true);

Practical Applications of Multi-Threaded Database Transactions

Database processing element of Adroitlogic Project-X is a good industrial level practical application of multi-threaded database transactions.

What Is Project-X?

Project X is the base framework for a new generation of redesigned integration products by Adroitlogic. Project-X consists of all the API definitions, core implementations of those APIs, messaging engine, message format definitions and implementations, metrics engine, etc. to be used by those integration products.

What Is a Database Processing Element?

The database connector and the database processing element provide the data persistent capabilities to Project-x. There are three main components to perform database operations: db egress connector, db ingress connector, and the db processing element. Database processing element supports for all four CRUD operations. Database egress connector provides create, update, delete operations and database ingress connector provides read operation in a timed manner.

How Transactions Are Used in The Database Processor

Let’s see how to configure an integration flow to perform a database transactional operation. Here we enter the data to a table, obtain the id of the last inserted row, and then again insert data to another table with the id obtained from the previous database operation.

Suppose there is a database table named as people having columns named as id, name, and age. The second table is named as students and the columns are id, school, and grade. Here, the id of the students table is a foreign key referenced from the people table.
Image title

The database transaction scope start element[1] starts the transaction scope. All the database operations happening within transaction scope are guaranteed to be committed if and only if all the operations within the transaction scope were a success. Then the clone message processing element[2] just takes a clone of the message and sends one copy as the response to the nio http ingress connector and the other copy to the database processor. Two new threads are created here and thread locals of the TransactionSynchronizationManager class are copied to the newly created threads. Then, database processing element[3] does the first insert to the people table in the database. Next, database processing element[5] reads the last inserted row from the people table and returns the result in DBResultsSetFormat. Then we use a custom processing element[6] to extract the id from the DBResultsSetFormat and set it to the header of the message. The last database processing element, element[7], does the second insert to the students table using the data read from the payload the id read from the message header. Finally, the database transaction scope end element closes the transaction scope and commit the changes to the database if all the operations are complete. The database transaction will be rolled back in any kind of failure within the transaction scope of the flow.

Spring MVC Execution Flow

f2SzS

Spring MVC 3.2 Execution Flow

Step 1: First request will be received by DispatcherServlet
Step 2: DispatcherServlet will take the help of HandlerMapping and get to know the Controller class name associated with the given request
Step 3: So request transfer to the Controller, and then controller will process the request by executing appropriate methods and returns ModeAndView object (contains Model data and View name) back to the DispatcherServlet
Step 4: Now DispatcherServlet send the model object to the ViewResolver to get the actual view page
Step 5: Finally DispatcherServlet will pass the Model object to the View page to display the result

That’s it :-)

Spring Bean Autowire by Autodetect

Practically bean dependencies are explicitly set in bean configuration files and it is really is a good practice to follow. But Spring is capable of automatically resolving dependencies at runtime. This automatic resolution of bean dependencies is also called autowiring. This type of bean dependencies can also be referred to as collaborating beans or just as collaborators.

There are 5 different types of autowiring modes which are ‘no’, ‘byName’, ‘byType’, ‘constructor’, and ‘autodetect’. In this post, I am taking down ‘autodetect‘ mode.

Autowiring by autodetect uses either of two modes i.e. constructor or byType modes. First it will try to look for valid 
constructor with arguments, If found the constructor mode is chosen. If there is no constructor defined in bean, or 
explicit default no-args constructor is present, the autowire byType mode is chosen.
Sections in this post:

Autowire dependency using autodetect
Create no-args constructor in bean
Test the dependency

Autowire dependency using autodetect

Autowiring by autodetect is enabled by using autowire=”autodetect” in bean definition in configuration file (i.e. application-context.xml).

A typical bean configuration file will look like this:

<?xml version="1.0" encoding="UTF-8"?>
    <context:annotation-config />
    
    <bean id="employee" class="com.howtodoinjava.autowire.autodetect.EmployeeBean" autowire="autodetect">
        <property name="fullName" value="Lokesh Gupta"/>
    </bean>
 
    <bean id="department" class="com.howtodoinjava.autowire.autodetect.DepartmentBean" >
        <property name="name" value="Human Resource" />
    </bean>
</beans>

Create no-args constructor in bean

In above configuration, I have enabled the autowiring by autodetect for ’employee’ bean. To use the byType mode, I must define either default constructor or no constructor at all.

package com.howtodoinjava.autowire.autodetect;
public class EmployeeBean
{
    private String fullName;
    
    private DepartmentBean departmentBean;
    public DepartmentBean getDepartmentBean() {
        return departmentBean;
    }
    public void setDepartmentBean(DepartmentBean departmentBean) {
        this.departmentBean = departmentBean;
    }
    public String getFullName() {
        return fullName;
    }
    public void setFullName(String fullName) {
        this.fullName = fullName;
    }
}

And DepartmentBean looks like this which has been set:

package com.howtodoinjava.autowire.autodetect;
public class DepartmentBean{
    private String name;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

Test the dependency

To test that bean has been set properly, run following code:

package com.howtodoinjava.autowire.autodetect;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestAutowire {
    public static void main(String[] args) {
        ApplicationContext context =
                  new ClassPathXmlApplicationContext(new String[] {"com/howtodoinjava/autowire/autodetect/application-context.xml"});
         
                EmployeeBean employee = (EmployeeBean)context.getBean("employee");
                System.out.println(employee.getFullName());
                System.out.println(employee.getDepartmentBean().getName());
    }
}
Output:
Lokesh Gupta
Human Resource

Clearly, dependency was injected by autodetect successfully.

Spring Bean Autowire by Constructor

Practically bean dependencies are explicitly set in bean configuration files and it is really is a good practice to follow. But Spring is capable of automatically resolving dependencies at runtime. This automatic resolution of bean dependencies is also called autowiring. This type of bean dependencies can also be referred to as collaborating beans or just as collaborators.

There are 5 different types of autowiring modes which are ‘no’, ‘byName‘, ‘byType‘, ‘constructor’, and ‘autodetect‘. In this post, I am taking down ‘constructor‘ mode.

Autowiring by constructor is similar to byType, but applies to constructor arguments. In autowire enabled bean, it will look for class type of constructor arguments, and then do a autowire by type on all constructor arguments.

Please note that if there isn’t exactly one bean of the constructor argument type in the container, a fatal error is raised.

Sections in this post:

Autowire dependency using constructor
Create constructor dependency
Test the dependency

Autowire dependency using constructor

Autowiring by constructor is enabled by using autowire="constructor" in bean definition in configuration file (i.e. application-context.xml).

A typical bean configuration file will look like this:

<?xml version="1.0" encoding="UTF-8"?>
    <context:annotation-config />
    
    <bean id="employee" class="com.howtodoinjava.autowire.constructor.EmployeeBean" autowire="constructor">
        <property name="fullName" value="Lokesh Gupta"/>
    </bean>
 
    <bean id="department" class="com.howtodoinjava.autowire.constructor.DepartmentBean" >
        <property name="name" value="Human Resource" />
    </bean>
</beans>
If you are not using autowire="constructor" in bean definition, then pass the constructor-arg as follow:

<bean id="employee" class="com.howtodoinjava.autowire.constructor.EmployeeBean">
    <property name="fullName" value="Lokesh Gupta"/>
    <constructor-arg>
        <ref bean="department" />
    </constructor-arg>
</bean>

Create constructor dependency

In above configuration, I have enabled the autowiring by constructor for ‘employee‘ bean. It has been done by passing constructor arguments.

package com.howtodoinjava.autowire.constructor;
public class EmployeeBean
{
    private String fullName;
    
    public EmployeeBean(DepartmentBean departmentBean)
    {
        this.departmentBean = departmentBean;
    }
    
    private DepartmentBean departmentBean;
    public DepartmentBean getDepartmentBean() {
        return departmentBean;
    }
    public void setDepartmentBean(DepartmentBean departmentBean) {
        this.departmentBean = departmentBean;
    }
    public String getFullName() {
        return fullName;
    }
    public void setFullName(String fullName) {
        this.fullName = fullName;
    }
}

And DepartmentBean looks like this which has been set:

package com.howtodoinjava.autowire.constructor;
public class DepartmentBean{
    private String name;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

Test the dependency

To test that bean has been set properly, run following code:

package com.howtodoinjava.autowire.constructor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestAutowire {
    public static void main(String[] args) {
        ApplicationContext context =
                  new ClassPathXmlApplicationContext(new String[] {"com/howtodoinjava/autowire/constructor/application-context.xml"});
         
                EmployeeBean employee = (EmployeeBean)context.getBean("employee");
                System.out.println(employee.getFullName());
                System.out.println(employee.getDepartmentBean().getName());
    }
}
Output:
Lokesh Gupta
Human Resource

Clearly, dependency was injected by constructor successfully.