-1

Following is sample class named 'Item' and It has one field named 'itemShop'.

Class Item{
    @Autowired
    Shop itemShop;
    ...
    ...
}

Main(){
    Item item1 = new Item();
    Item item2 = new Item();
    // item1 and item2 both should have same 'itemShop' object.
}

I want that for all objects item1,item2 ... item_n, I have only one instance of 'itemShop'. I am new in Java and I want to know is there any way I can use 'Autowired' annotation to have single instance of 'itemShop' field in whole program.

Pirate_Jack
  • 138
  • 1
  • 3
  • 11
  • If you have a single `Shop` bean and you correctly get your `Item` beans from the application context instead of instantiating them yourself, that will be the default behavior. – Sotirios Delimanolis Nov 23 '15 at 16:55
  • Actually I can't instantiate Item class in application context since we have to explicitly instantiate many times in whole program. – Pirate_Jack Nov 23 '15 at 16:59
  • You can do that with _prototype_ beans. If you're going to instantiate it yourself, Spring will not know anything about it and therefore won't be able to process `@Autowired`. – Sotirios Delimanolis Nov 23 '15 at 17:00
  • 1
    If the Shop bean is configured to be a Singleton in Spring (it's the default behavior), you should have always the same object from Spring. I assume that in some point in your program the Shop object will be associated with the Item object (in a setter method?). You didn't provide any more details on what you're trying to achieve, but be careful, in general singleton objects shouldn't have any shared state. – Vitor Santos Nov 23 '15 at 17:45
  • Pass the `Shop` as a constructor parameter. – chrylis -cautiouslyoptimistic- Nov 23 '15 at 18:19

2 Answers2

1

If your Shop instance is created with default spring behaviour it is singleton and you already got what you want

k0ner
  • 1,086
  • 7
  • 20
0

You can use Spring's @Configurable annotation on your Item class

@Configurable
Class Item{

    @Autowired
    Shop itemShop;

}

Using AOP, Spring will automatically autowire all necessary beans even when you instantiate the Item object yourself.

See the documentation here :

http://docs.spring.io/spring/docs/current/spring-framework-reference/html/aop.html#aop-atconfigurable

Similar question here :

Spring autowiring using @Configurable

Community
  • 1
  • 1
wesker317
  • 2,172
  • 1
  • 16
  • 11