简体   繁体   中英

Get bean with dynamic constructor arguments

I have a spring component that has an @Autowired constructor that takes its arguments from @Value annotations. Like this:

@Component
public class MyImplClass implement MyInterface
...
public MyImplClass(@Value("${prop.name}") final String name, @Value("${prop.value}") final String value) {
...
}
...

in another class i autowire this type like so

@Autowired
protected MyInterface _myInterface;

now I need to get the MyInterface bean with dynamically generated values (generated in runtime) passed to the constructor. I tried to use an AbstractBeanFactory but this didn't work. How do i do this?

You could produce a bean in your Spring config like this:

@Bean
public MyInterface getMyInterfaceBean() {
    // Calculate arg values
    String arg1 = ...;
    String arg2 = ...;
    return new MyImplClass(arg1, arg2);
}

Even better solution would be to change the constructor of MyImplClass to receive a configuration object which will know how to load the required values.

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