通常在Spring中啓用註釋(例如@Autowired)是通過將其包含在Spring XML中來完成的。如何以編程方式在Spring中啓用「annotation-config」ApplicationContext
<context:annotation-config/>
有沒有一種方法可以在初始化它之前在ApplicationContext(或實現)上以編程方式執行此操作?
通常在Spring中啓用註釋(例如@Autowired)是通過將其包含在Spring XML中來完成的。如何以編程方式在Spring中啓用「annotation-config」ApplicationContext
<context:annotation-config/>
有沒有一種方法可以在初始化它之前在ApplicationContext(或實現)上以編程方式執行此操作?
只需在@Configuration類中使用AnnotationConfigApplicationContext類就足夠了。基於java的容器配置不依賴於以任何方式進行組件掃描。它對於基於XML的組件配置僅僅是一種不同的方法。
經過這些鏈接:
Spring annotations - @Configuration to invoke spring bean auto-building
如果你真的需要這個技巧,你可以看看AnnotationConfigBeanDefinitionParser.parse()
以檢查它是如何操縱的背景和它註冊什麼樣的bean定義使用它,然後嘗試使用ApplicationContext實現以編程方式重現,以實現相同的效果。
This post可能會幫助您如何將新的bean定義添加到bean註冊表中。
我掙扎了很多與這一個,作爲一種解決方法我創建了一個簡單的彈簧方面-config.xml文件中有如下內容
<?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/>
,並增加一條,作爲進口到我的應用程序上下文類
@ImportResource("classpath:spring-aspect-config.xml")
編程可以通過指定
012做同樣的對您的應用程序上下文類。