有没有办法只使用注释从同一个类声明两个spring bean实例?

рüф*_*ффп 3 java spring annotations

我通常使用XML Spring配置(spring-conf.xml)来执行此操作:

<beans>

    <context:component-scan base-package="org.company.dept.business" />
   ... 
    <bean id="myServiceB2B" class="org.company.dept.business.service.MyService"
        p:configLocation="WEB-INF/classes/b2b.properties" />

    <bean id="myServiceResidential" class="org.company.dept.business.service.MyService"
        p:configLocation="WEB-INF/classes/residential.properties" />
   ...

</beans>
Run Code Online (Sandbox Code Playgroud)

因为MyService类只有一个文件(定义),有没有办法在不使用XML Spring配置的情况下实例化两个bean?

我对XML定义没问题,但我总是尽量减少我的XML配置.

Sot*_*lis 12

<bean>在XML中使用2个声明的方式相同,@Bean在Java配置中使用2个带注释的类.

@Configuration
public class MyConfiguration {
    @Bean(name = "firstService")
    public MyService myService1() {
        return new MyService();
    }

    @Bean(name = "secondService")
    public MyService myService2() {
        return new MyService();
    }
}
Run Code Online (Sandbox Code Playgroud)

我不知道configLocation它的用途,但你也可以在Java配置中包含它.

name属性@Bean相当于id属性<bean>.