![](/img/trans.png)
[英]Spring configuration in Java - Create and use 2 beans of same class NOT using Autowired
[英]Is it possible to create some beans using xml and the remaining beans using annotation based approach in the same java web application
我有一個Web項目,其中使用Spring Java注釋注入了bean。 現在在同一個Web項目中,我想使用基於xml的配置來創建幾個bean。 (我很難在這里提供詳細說明,為什么要這樣做)。 為此,我在web.xml
指定了ContextLoaderListener
和contextConfigLocation
。 完成此操作后,當我在服務器上部署項目戰時,我發現僅創建了使用xml( applicationContext.xml
)創建的那些bean,Spring無法創建和注入使用基於注釋的方法創建的bean。
是否可以實現這種用例類型,即為同一項目使用批注創建一些Bean,並使用applicationContext.xml創建某些用例? 如果是的話,我將不勝感激。
謝謝。
嘗試類似的東西:
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.context.annotation.Bean;
@Configuration
@ImportResource("spring-xml-configuration-file.xml")
public class ConfigClass {
...
@Bean
public Object bean1() {
...
}
}
@ Configuration指定您的java類是Spring的配置。 @TmportResource允許這些類使用xml配置文件中定義的bean。
是的,可能。
您需要在applicationContext.xml
添加以下<context:component-scan />
標記,以識別帶注釋的spring Bean並將其實例化。
applicationContext.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-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd"> <!-- Annotated beans base package location to get it instantiated at the time of spring context startup --> <context:component-scan base-package="com.example.service.beans"/> <!-- normal bean configured in xml --> <bean id="userDao" class="com.example.dao.UserDao" /> </beans>
在上述基本軟件包下存在的所有帶注釋的bean將與在xml文件中配置的普通bean( <beans/>
)一起實例化。 不要忘記將spring-context-<version>.xsd
到applicationContext.xml
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.