Announcement Announcement Module
Collapse
No announcement yet.
How to inject a bean with constructor arguments using @Autowrire Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • How to inject a bean with constructor arguments using @Autowrire

    Hi,

    Is there anyway to use the Autowire annotation to inject a bean which has a constructor into a class using the @Autowire annotation?

    In XML, it is easy to configure the bean information with <constructor-args>, but is there any way to do something similar using the annotation?

    Thanks,

    Eric

  • #2
    You mean if the @Autowired annotation can be applied on constructors?

    Code:
    public class Sample {
        private A a;
    
        @Autowired
        public Sample (A a) {
            this.a= a;
        }
    }

    Comment


    • #3
      No. Actually, I meant more as a class member:

      Ex:
      Code:
      @Component
      public class MyConstructorClass{
      
        String var;
        public MyConstructorClass( String var ){
          this.var = var;
        }
      ...
      }
      
      
      @Service
      public class MyBeanService{
        @Autowired
        MyConstructorClass myConstructorClass;
      
        ....
      }
      In this example, how do I specify the "String var" variable required by MyConstructorClass. If I was using an XML configuration file, I'd be able to use <constructor-args> to specify the value, but how do I do that with the @Autowire annotation?

      Thanks,

      Eric

      Comment


      • #4
        <bump>

        Sorry to make this shameless bump, but I'm really stuck on this issue and was really hoping that someone could help me out here. Is there no way to Annotation autowire a bean that requires constructor arguments?

        Thanks,

        Eric

        Comment

        Working...
        X