2

In my spring context I am creating a service bean and a proxy for this service bean (explicitly). Both implement the same interface.

Can I ensure that autowiring cannot inject the target bean?

I would like to be able to use the target service with the @Resource or @Qualifier annotations, but when autowiring it should always be the proxy.

Any ideas?

Dennis Thrysøe
  • 1,791
  • 4
  • 19
  • 31
  • Maybe this post could help you http://stackoverflow.com/questions/10534053/autowiring-two-beans-implementing-same-interface-how-to-set-default-bean-to-au – jmventar Feb 19 '13 at 10:26
  • What does the proxy do? How do you create you application context (xml, java, annotation scanning)? – Philippe Marschall Feb 19 '13 at 12:20
  • The proxy is a facade for the target bean. The context is created in xml, but with custom namespace, a custom parser, and the proxy created with a BeanFactory. – Dennis Thrysøe Feb 20 '13 at 10:51

2 Answers2

2

Use the Primary annotation. It will indicate which bean should be use preferably when autowiring.

Hope this helps :)

Caesar Ralf
  • 2,203
  • 1
  • 18
  • 36
  • 1
    There's also an XML attribute `primary="true"` if you're using XML configuration. This configuration tells Spring to always use this bean if there are multiple candidate beans for autowiring. – Philipp Jardas Feb 24 '13 at 12:16
0

You can put @Primary annotation in your proxy service like bellow:

@Primary
@Repository
public class ProxyOfSomeService implements SomeService

And after that when you use, @Autowired annotation on SomeService field, the ProxyOfSomeService will be injected by deafault.

But when you need the real service you can have it like bellow:

@Autowired
@Resource(name="someRealService")
private SomeService someService;

I think this serves your need, thanks!

Sazzadur Rahaman
  • 6,938
  • 1
  • 30
  • 52