0

Is it possible?

Here is a more detailed case:

class A {
    private service x;

    //other members
    //some more methods.
}

bean definition is available for service but I do not want class A to be a spring bean and neither x to be static.

Is this achievable.

EDIT:

My spring configuration:

<bean id="Service" class="com.xx.yy.Service" />
<--!I do not register class A as a bean. Hence cannot use @autowired directly.-->
Aman Deep Gautam
  • 8,091
  • 21
  • 74
  • 130
  • Do you wanr service in class A to be managed by spring? – Darshan Lila Aug 04 '14 at 08:48
  • @DarshanLila yes. but not the whole class. I have a bean for the service but I just want to initialize the data member in this class. – Aman Deep Gautam Aug 04 '14 at 08:52
  • If you don't tell spring that your class A is a bean (using annotation or XML), spring won't manage them. – Athanor Aug 04 '14 at 08:54
  • @Athanor I am not asking spring to manage them. I just need a way to assign a data member which is managed by spring. – Aman Deep Gautam Aug 04 '14 at 09:40
  • Check out @Autowired with component scan – Darshan Lila Aug 04 '14 at 10:23
  • @DarshanLila Hope you are talking about this:http://stackoverflow.com/questions/7414794/difference-between-contextannotation-config-vs-contextcomponent-scan. This needs the bean to be regiested with @Compoment, if I am not wrong. I do not want to register `class A` as a bean. – Aman Deep Gautam Aug 04 '14 at 12:19
  • @Athanor I have edited the question with more details. Here is a very similar question but the members are that need to be assigned are static:http://stackoverflow.com/questions/11324372/how-to-make-spring-inject-value-into-a-static-field – Aman Deep Gautam Aug 04 '14 at 12:26

2 Answers2

0

I think you should create the factory for instances of class A which should take care of setting x.

@Service
class FactoryA {

  @Autowired service x;

  public A create() {
    return new A(x);
  }

}
slavik
  • 1,223
  • 15
  • 17
0

It can only be achieved by manually getting the bean from the context.

Service service = context.getBean(Service.class);
A a = new A(service);
Bart
  • 17,070
  • 5
  • 61
  • 80
  • is something close to this: http://stackoverflow.com/questions/11324372/how-to-make-spring-inject-value-into-a-static-field not possible. – Aman Deep Gautam Aug 04 '14 at 15:14