Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to declare two spring beans instance from the same class with annotation only?

I usually use the XML Spring configuration (spring-conf.xml) for doing it like this:

<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>

Because there is only one file (definition) of the class MyService is there a way to instantiate the two beans without using the XML Spring configuration?

I am ok with the XML definition but I am always trying to minimise my XML configuration as much as possible.

like image 924
рüффп Avatar asked Dec 02 '22 21:12

рüффп


1 Answers

In the same way you would use 2 <bean> declarations in XML, you use 2 @Bean annotated classes in Java configuration.

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

    @Bean(name = "secondService")
    public MyService myService2() {
        return new MyService();
    }
}

I don't know what the configLocation is for, but you can definitely include that in the Java config as well.

The name attribute of @Bean is equivalent to the id attribute of <bean>.

like image 190
Sotirios Delimanolis Avatar answered Jan 01 '23 03:01

Sotirios Delimanolis