Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why @PostConstruct method is not called when autowiring prototype bean with constructor argument

Tags:

I have a prototype-scope bean, which I want to be injected by @Autowired annotation. In this bean, there is also @PostConstruct method which is not called by Spring and I don't understand why.

My bean definition:

package somepackage;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;

@Component
@Scope("prototype")
public class SomeBean {

    public SomeBean(String arg) {
        System.out.println("Constructor called, arg: " + arg);
    }

    @PostConstruct
    private void init() {
        System.out.println("Post construct called");
    }

}

JUnit class where I want to inject bean:

package somepackage;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@ContextConfiguration("classpath*:applicationContext-test.xml")
public class SomeBeanTest {

    @Autowired
    ApplicationContext ctx;

    @Autowired
    @Value("1")
    private SomeBean someBean;

    private SomeBean someBean2;

    @Before
    public void setUp() throws Exception {
        someBean2 = ctx.getBean(SomeBean.class, "2");
    }

    @Test
    public void test() {
        System.out.println("test");
    }
}

Spring configuration:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd">

    <context:component-scan base-package="somepackage"/>

</beans>

The output from execution:

Constructor called, arg: 1
Constructor called, arg: 2
Post construct called
test

When I initialize bean by calling getBean from ApplicationContext everything works as expected. My question is why injecting bean by @Autowire and @Value combination is not calling @PostConstruct method

like image 479
gerard Avatar asked Feb 27 '18 11:02

gerard


People also ask

When @PostConstruct is invoked?

The PostConstruct annotation is used on a method that needs to be executed after dependency injection is done to perform any initialization. This method MUST be invoked before the class is put into service. This annotation MUST be supported on all classes that support dependency injection.

When @PostConstruct is called in Java?

2. @PostConstruct. Spring calls the methods annotated with @PostConstruct only once, just after the initialization of bean properties. Keep in mind that these methods will run even if there's nothing to initialize.

Can we Autowire prototype bean?

When you autowire a prototype bean, Spring will initialize a new instance of the bean. If you autowire the bean in multiple places, then Spring will create a new instance for every place you autowire the bean. Let us demonstrate this behavior by creating a test bean and a spring test where we autowire our test beans.

What is @PostConstruct annotation in Spring?

When we annotate a method in Spring Bean with @PostConstruct annotation, it gets executed after the spring bean is initialized. We can have only one method annotated with @PostConstruct annotation. This annotation is part of Common Annotations API and it's part of JDK module javax.


2 Answers

Why is @Value used instead of @Autowired?

The @Value annotation is used to inject values and normally has as destination strings, primitives, boxed types and java collections.

Acording to Spring's documentation:

The @Value annotation can be placed on fields, methods and method/constructor parameters to specify a default value.

Value receives a string expression which is used by spring to handle the conversion to the destination object. This conversion can be through the Spring's type conversion, the java bean property editor, and the Spring's SpEL expresions. The resulting object of this conversion, in principle, is not managed by spring (even though you can return an already managed bean from any of this methods).

By the other hand, the AutowiredAnnotationBeanPostProcessor is a

BeanPostProcessor implementation that autowires annotated fields, setter methods and arbitrary config methods. Such members to be injected are detected through a Java 5 annotation: by default, Spring's @Autowired and @Value annotations.

This class handles the field injection, resolves the dependencies, and eventually calls the method doResolveDependency, is in this method where the 'priority' of the injection is resolved, springs checks if a sugested value is present which is normally an expression string, this sugested value is the content of the annotation Value, so in case is present a call to the class SimpleTypeConverter is made, otherwise spring looks for candicate beans and resolves the autowire.

Simply the reason @Autowired is ignored and @Value is used, is because the injection strategy of value is checked first. Obviously always has to be a priority, spring could also throw an exception when multiple conflicting annotations are used, but in this case is determined by that previous check to the sugested value.

I couldn't find anything related to this 'priority' is spring, but simple is because is not intended to use this annotations together, just as for instance, its not intended to use @Autowired and @Resource together either.


Why does @Value creates a new intance of the object

Previously I said that the class SimpleTypeConverter was called when the suggested value was present, the specific call is to the method convertIfNecessary, this is the one that performs the conversion of the string into the destination object, again this can be done with property editor or a custom converter, but none of those are used here. A SpEL expression isn't used either, just a string literal.

Spring checks first if the destination object is a string, or a collection/array (can convert e.g. comma delimited list), then checks if the destination is an enum, if it is, it tries to convert the string, if is not, and is not an interface but a class, it checks the existance of a Constructor(String) to finally create the object (not managed by spring). Basically this converter tries many different ways to convert the string to the final object.

This instantiation will only work using a string as argument, if you use for instance, a SpEL expression to return a long @Value("#{2L}"), and use an object with a Constructor(Long) it will throw an IllegalStateException with a similar message:

Cannot convert value of type 'java.lang.Long' to required type 'com.fiberg.test.springboot.object.Hut': no matching editors or conversion strategy found


Possible Solution

Using a simple @Configuration class as a supplier.

public class MyBean {
    public MyBean(String myArg) { /* ... */ }
    // ...
    @PostConstruct public init() { /* ... */ }
}

@Configuration
public class MyBeanSupplier {
    @Lazy
    @Scope(scopeName = ConfigurableBeanFactory.SCOPE_PROTOTYPE, 
           proxyMode = ScopedProxyMode.NO)
    public MyBean getMyBean(String myArg) {
        return new MyBean(myArg);
    }
}

You could define MyBean as a static class in MyBeanSupplier class if its the only method it would have. Also you cannot use the proxy mode ScopedProxyMode.TARGET_CLASS, because you'll need to provide the arguments as beans and the arguments passed to getMyBean would be ignored.

With this approach you wouldn't be able to autowire the bean itself, but instead, you would autowire the supplier and then call the get method.

// ...
public class SomeBeanTest {
    @Autowired private MyBeanSupplier supplier;
    // ...
    public void setUp() throws Exception {
        someBean = supplier.getMyBean("2");
    }
}

You can also create the bean using the application context.

someBean = ctx.getBean(SomeBean.class, "2");

And the @PostConstruct method should be called no matter which one you use, but @PreDestroy is not called in prototype beans.

like image 180
Jose Da Silva Avatar answered Oct 21 '22 06:10

Jose Da Silva


I read through the debug logs and stack trace for both scenarios many times and my observations are as follows:-

  1. When it goes to create the bean in case of @Autowire, it basically ends up injecting value to the constructor via using some converters. See screenshot below:-

converters are used

  1. The @Autowire is ineffective. So, in your code, if you even remove @Autowired it will still work. Hence, supporting #1 when @Value is used on property it basically created the Object.

Solution:-

You should be having a bean with name arg injected with whatever value you want. E.g. I preferred using configuration class(you could create the bean in context file) and did below:-

@Configuration
public class Configurations {

    @Bean
    public String arg() {
        return "20";
    }
}

Then test class would be as below (Note you could use change ContextConfiguration to use classpath to read context file ):-

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {SomeBean.class, Configurations.class})
public class SomeBeanTest {

    @Autowired
    ApplicationContext ctx;

    @Autowired
    String arg;

    @Autowired
    private SomeBean someBean;

    private SomeBean someBean2;

    @Before
    public void setUp() throws Exception {
        someBean2 = ctx.getBean(SomeBean.class, "2");
    }

    @Test
    public void test() {
        System.out.println("\n\n\n\ntest" + someBean.getName());
    }
}

So, a learning for me as well to be careful with the usage of @Value as it could be misleading that it helped in autowiring by injecting value from some spring bean that got created in the background and could make applications misbehave.

like image 39
Vinay Prajapati Avatar answered Oct 21 '22 06:10

Vinay Prajapati