2

let me demonstrate with code :

public interface A {
  ....
}

@Profile({"V1"})
@Component
public class B implements A {
....
}

@Profile({"V2"})
@Component
public class C implements A {
....
}

How can i dynamically (on every request that arrives) make spring to autowire one of above classes according to their profile? is it even possible to do such a thing at wiring time?

background : i am seeking a good practice to implement server side version control mechanism. if a request belongs to version 'V1' i want to autowire a class with 'V1' profile and vice versa. (currently i am autowiring a list and iterating them to find the suitable version).

MoienGK
  • 4,544
  • 11
  • 58
  • 92
  • 2
    No, this is not possible. The spring beans are created at server startup. You will need to rethink your implementation. – jax May 03 '15 at 05:26

4 Answers4

2

is it even possible to autowire bean in every request?

No it's not possible. Beans are injected when the context is created.

I am seeking a good practice to implement server side version control mechanism

You can follow this answer How to manage REST API versioning with spring?

Community
  • 1
  • 1
mirmdasif
  • 6,014
  • 2
  • 22
  • 28
1

The answer is No, because when you try to activate multiple profiles in spring like -Dspring.profiles.active=profile1,profile2and both profiles contains bean that implements A then spring will use the last active definition of the bean that implements A i.e. B in your case.

sol4me
  • 15,233
  • 5
  • 34
  • 34
  • If two beans are found, a `NoUniqueBeanDefinitionException` is thrown. – dunni May 03 '15 at 05:41
  • It is thrown thrown when a `BeanFactory` is asked for a bean instance for which multiple matching candidates have been found when only one matching bean was expected. – sol4me May 03 '15 at 05:43
  • Yes, that's exactly what would be the case, when both profiles are active (multiple candidates would be found). Of course, if the injection point is a collection, both instances would be injected in the collection, otherwise the said exception is thrown. – dunni May 03 '15 at 09:10
0
public interface A {
  ....
}

@Profile({"V1"})
@Service("bean1")
public class B implements A {
....
}

@Profile({"V2"})
@Service("bean2")
public class C implements A {
....
}

now the third class:

class D {
@Autowired
@Qualifier("bean1")
private A a;

}

i hope to help you

reza ramezani matin
  • 1,384
  • 2
  • 18
  • 41
-2

you use @Qualifier annotation where you want to inject above interface

reza ramezani matin
  • 1,384
  • 2
  • 18
  • 41