简体   繁体   中英

@Autowired Foo foo, if Foo is not a @Component

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:

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM