0

I would like to auto-wire foo:

@Autowired
Foo foo

but I cannot modify class Foo and mark it as @Component. What is the cleanest way to autowire foo?

BTW, I would prefer to use Java Spring configuration instead of XML config if you need to use config to address this problem.

Related:

Community
  • 1
  • 1
Jakub M.
  • 32,471
  • 48
  • 110
  • 179

2 Answers2

4

The @Bean annotation seems to be what you're after...

In your Javaconfig class you would create an @Bean annotated method returning Foo:

@Bean
public Foo foo() {
    return new Foo();
}

See: http://docs.spring.io/spring-javaconfig/docs/1.0.0.M4/reference/html/ch02s02.html

rbrtl
  • 791
  • 1
  • 6
  • 23
1

You can use an xml configuration file to create a bean of the class Foo. Then @Autowired works the same as annotating the beans directions.

Sample xml file:

<beans>
  <bean id="foo" class="Foo"/>
</beans>

If you now include this into your file with the autoscan then this bean is used as if it were annotated with @Component.

Uwe Plonus
  • 9,803
  • 4
  • 41
  • 48