简体   繁体   中英

Multiple instances of a bean Spring

I have a config file in spring which I want to define a constructor parameter for each instance of a particular @Component that I have in spring. How can I do that?

@Component
public class MyComponent {
    public MyComponent(String config) {}
}

and in my application.yml I want to define something like this:

myconfig:
   - config1
   - config2
   - config3

I would like to make spring create one instance per config entry in the application.yml . Is that possible? Thanks

You want to create 3 beans with one annotation? Not possible as far as I know. Why not create 3 subclasses and pull in the configuration values with @Resource annotations? And btw: you must provide a default constructor, because that is the one being called.

There's no way to do this automatically with Spring. You would have to define the beans individually probably by subclassing as @Mick suggested. Firstly, remove the @Component annotation from the base class:

public class MyComponent {
    public MyComponent(String config) {}
}

Create however many extensions of this you require as @Components for each config: eg:

@Component
public class MyComponentConfig1 extends MyComponent {

    public MyComponentConfig1(@Value("myconfig.config1") String config) {
          super(config);
    }

}

Where the values are injected into your constructor for you by Spring when registering the beans.

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