Alex D
Alex D

Reputation: 663

Factory defined bean is not enhanced by Micronaut

Applying @Singleton directly on a service class, that contains @PostConstruct and @Transactional works as expected - @PostConstruct is called and the transactional method works just fine.

@Singleton
public class MyService {

    @PostConstruct
    public void init() {
       LOG.info("PostConstruct called")
    }

    @Transactional
    public void doSomethingInTransaction() {

    }

}

Moving the bean definition into a @Factory like below still works, MyService singleton is still created but it's not being enhanced - @PostConstruct is not called and transactional method won't work (Could not obtain transaction-synchronized Session for current thread)

public class MyService {

    @PostConstruct
    public void init() {
       LOG.info("PostConstruct called")
    }

    @Transactional
    public void doSomethingInTransaction() {

    }

}

@Factory
public class ApplicationConfig {

    @Singleton
    public MyService myService() {
        return new MyService();
    }

}

Is this an expected behavior of Micronaut compared with Spring? Is there any way to instruct Micronaut to handle the bean defined in external Java config the same as the ones defined in their own class?

Note: I've noticed that Micronaut will apply transaction management if I add @TransactionalAdvice like below (although in java doc is stated that it shouldn't be used directly) - but @PostConstruct still doesn't work.

@Factory
public class ApplicationConfig {

    @Singleton
    @TransactionalAdvice
    public MyService myService() {
        return new MyService();
    }

}

Upvotes: 1

Views: 1331

Answers (1)

James Kleeh
James Kleeh

Reputation: 12238

The behavior is expected.

You can just execute the init method manually after creating the instance

We don't analyze the classes returned by factories beyond what annotations are on the factory method because you should only be using factories for classes that you aren't in control of (ie are in a third party jar). In that case it should not be expected that those annotations exist because if the class is designed for injection via DI then you wouldn't be using a factory to create it.

Upvotes: 4

Related Questions