Is there a way to @Autowire a bean that requires constructor arguments?

Eric B. picture Eric B. · Jul 18, 2011 · Viewed 164.8k times · Source

I'm using Spring 3.0.5 and am using @Autowire annotation for my class members as much as possible. One of the beans that I need to autowire requires arguments to its constructor. I've looked through the Spring docs, but cannot seem to find any reference to how to annotate constructor arguments.

In XML, I can use as part of the bean definition. Is there a similar mechanism for @Autowire annotation?

Ex:

@Component
public class MyConstructorClass{

  String var;
  public MyConstructorClass( String constrArg ){
    this.var = var;
  }
...
}


@Service
public class MyBeanService{
  @Autowired
  MyConstructorClass myConstructorClass;

  ....
}

In this example, how do I specify the value of "constrArg" in MyBeanService with the @Autowire annotation? Is there any way to do this?

Thanks,

Eric

Answer

Sean Patrick Floyd picture Sean Patrick Floyd · Jul 18, 2011

You need the @Value annotation.

A common use case is to assign default field values using "#{systemProperties.myProp}" style expressions.

public class SimpleMovieLister {

  private MovieFinder movieFinder;
  private String defaultLocale;

  @Autowired
  public void configure(MovieFinder movieFinder, 
                        @Value("#{ systemProperties['user.region'] }") String defaultLocale) {
      this.movieFinder = movieFinder;
      this.defaultLocale = defaultLocale;
  }

  // ...
}

See: Expression Language > Annotation Configuration


To be more clear: in your scenario, you'd wire two classes, MybeanService and MyConstructorClass, something like this:

@Component
public class MyBeanService implements BeanService{
    @Autowired
    public MybeanService(MyConstructorClass foo){
        // do something with foo
    }
}

@Component
public class MyConstructorClass{
    public MyConstructorClass(@Value("#{some expression here}") String value){
         // do something with value
    }
}

Update: if you need several different instances of MyConstructorClass with different values, you should use Qualifier annotations