简体   繁体   中英

Spring dependency injection to a class with a constructor

I'm kind of new to the whole spring dependency injection. There is one thing that I don't understand and hopefully someone could clear that up for me...

I have a service:

@Service
public class Service {...}

And another class:

public class A{
   @Autowired
   private Service service;
   ...
}

In this case, Service will be injected into class A as expected. As far as I know, you cannot use a constructor in class A, otherwise the injection will not work. Is there a way to use a constructor in class A and inject Service at the same time? ie:

public class A{
       @Autowired
       private Service service;

       private String a;
       private int b;
       public A(String a,int b){
        this.a = a;
        this.b = b;
       }
    }

In this case I'm getting that service is null, anyway to work that out? I want to be able to create an object from type A using "new" with the Service injected to it, is that possible?

Thanks.

The important bit is that both of your classes should be Spring beans.

This in turn means that all the instantiation will be done by Spring container. To learn how to properly handle constructor-based dependency injection, check this bit of ref doc

If whysoever, you can't make a class A a Spring bean, than the recommended way is to annotate it with @Configurable which will autowire dependencies on creation time.

Note that for this, you'll need to enable aspects. I did a quick search and found this blog that seems to do a good job explaining the details

There is. You should manually create the instance of your service class in a Spring configuration class (annotated with @Configuration ) and annotate the method that creates the instance with @Service , instead of the class.

So, as an example, your application might have a Spring configuration that looks like this:

@Configuration
public class MyApplicationConfig {
    @Bean
    public Service myService() {
        return new Service("hello", "world", 42); // ctor args as an example
    }
}

And your service class:

// need fully qualified class because your class has the same name
@org.springframework.stereotype.Service
public class Service {
    public Service(String prefix, String suffix, int number) {
        // Whatever
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM