0

I was reading this post when I thought about the possibility of substituting any @Bean (Spring DI) or @Produces (CDI) with a simple @PostConstructor as in the following CDI example:

Replace:

public class MyClassFactory {

    @Produces
    @RequestScoped
    public MyClass createMyClass() {
        MyClass myClass = new MyClass();
        myClass.setA(1);
        return myClass;
    }
}

public class MyClass {

    private int a;

    private void setA(int a) {
        this.a = a;
    }
}

With:

public class MyClass {

    @PostConstruct
    public void init() {
        this.setA(1);
    }

    private int a;

    private void setA(int a) {
        this.a = a;
    }
}

Is that correct? What are the differences between those options?

falsarella
  • 12,217
  • 9
  • 69
  • 115

2 Answers2

1

No, @PostConstruct defines an interceptor for the initialization of a bean. It cannot be used to define the instantiation of a bean.

falsarella
  • 12,217
  • 9
  • 69
  • 115
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
0

I dont see this as an incorrect question.

@PostConstruct method is invoked after the default constructor invocation and dependency injection (if any) are finished. You can initialize instance variables of a bean using the within a @PostConstruct annotated method. In this case, the difference b/w using @PostConstruct and CDI is that, the instance returned by CDI is a contextual one and since it is @RequestScoped, the lifetime of the 'produced' bean is confined to one HTTP request. A new instance of the bean would be produced once the existing HTTP request is complete. In case of @PostConstruct, its an @Dependent scoped bean (by default) and its life cycle would 'depend' upon the bean which injects it (using CDI @Inject)

Abhishek
  • 1,175
  • 1
  • 11
  • 21
  • Are you telling that the replacement is fine? I asked about the difference between the `@Produces`/`@Bean` approach and the possible `@PostConstruct` approach, not the difference between Spring DI and CDI. Sorry if I wasn't clear. – falsarella Apr 10 '15 at 18:44