Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Postconstruct is called twice for programmaticaly created bean #11656

Open
loicmathieu opened this issue Mar 13, 2025 · 3 comments
Open

Postconstruct is called twice for programmaticaly created bean #11656

loicmathieu opened this issue Mar 13, 2025 · 3 comments

Comments

@loicmathieu
Copy link

Expected Behavior

When a bean is created manually then registed via regiserSingleton, if it has a method annoted with @PostConstruct this method must be called once.

Actual Behaviour

Take as example the following bean:

@Singleton
public class MyBean {

    @PostConstruct
    void init() {
        System.out.println("MyBean init " + this);
    }

    public String hello() {
        return "hello";
    }
}

When constructed then registered programmatically like that:

public class Application {

    public static void main(String[] args) {
        ApplicationContext applicationContext = Micronaut.run(Application.class, args);
        MyBean bean = applicationContext.createBean(MyBean.class);
        applicationContext.registerSingleton(bean);

        System.out.println(bean.hello());
    }
}

The postconstruct method is called twice.

Steps To Reproduce

double-postconstruct.zip

Environment Information

Example Application

No response

Version

4.7.6

@graemerocher
Copy link
Contributor

I don't think this is a supported pattern (ie. calling createBean and then registerSingleton). Changing this behaviour my break existing users as well.

@loicmathieu
Copy link
Author

The documentation of createBean says that the singleton is not registered so I had to register it manually if I want to be able to inject it.

I create beans conditionally, in a command, with parameters passed as command line options so I had to use createBean.

Maybe a solution would be to create the bean with new, manually do injection (applicationContext.init()) then register it?

@graemerocher
Copy link
Contributor

createBean is normally not used in combination with @Singleton because a singleton is... well singleton, there is only one

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants