问题
Normally enabling annotations in spring such as @Autowired is done by including this in the spring XML.
<context:annotation-config/>
Is there a way I can do this programmatically on the ApplicationContext (or implementation) before initialising it?
回答1:
Simply using the AnnotationConfigApplicationContext class in the @Configuration class is sufficient. The java based container configuration doesn't depend on doing a component scan in any way. Its merely a different approach for the XML based component configuration.
Go through these links :
coderanch
Spring annotations - @Configuration to invoke spring bean auto-building
回答2:
I struggled a lot with this one, as a workaround i created a simple spring-aspect-config.xml file with following content
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:spring-configured/>
and added it as import to my Application context class
@ImportResource("classpath:spring-aspect-config.xml")
Programmatically you can do the same by specifying
@EnableSpringConfigured
on you application context class.
Reference - https://jira.springsource.org/browse/SPR-7888
回答3:
If you really need this hack, you could look at AnnotationConfigBeanDefinitionParser.parse()
to check how it manipulates the context and what kind of bean definitions it registers with it, then try to reproduce that programmatically using the ApplicationContext implementation to achieve the same effects.
This post may help on how to add new bean definitions to the bean registry.
来源:https://stackoverflow.com/questions/15158046/how-do-i-programmatically-enable-annotation-config-in-spring-applicationcontex