Larry White
Larry White

Reputation: 1

How can I access Spring beans in no-arg constructor?

@Component
public class MyClass {
    public MyClass() {
        SomeInterface something;

        // Spring magic that i don't know

        something.toString();
    }
}

What Spring magic do I need to use to inject a bean into "something"?

I also wouldn't mind if it was a field. It just has to be usable from within the constructor!

Upvotes: 0

Views: 768

Answers (1)

JB Nizet
JB Nizet

Reputation: 691735

The basic rules also apply to Spring:

  • to construct an object, Spring needs to invoke the constructor
  • Spring can't call a method of an object or set one of its fields if it isn't constructed yet
  • so if you want to access a field set by Spring , you can't do that from the constructor, unless the value is passed as argument to the constructor.

This thus leaves two choices:

  1. constructor injection:

    @Autowired
    public MyClass(SomeInterface something) {
        // use something
    }
    
  2. post-construct method, called after all the injections have been done, whatever the way:

    @Autowired
    private SomeInterface something;
    
    @PostConstruct
    private void initialize() {
        // use something
    }
    

Upvotes: 1

Related Questions